I'm using a basic javascript email validation function and am trying to use jQuery to submit the form if conditions are met. However, the submit() function doesn't seem to be running for the email validation is met.
HTML
<form id="profile" action="" method="post">
<input type="text" id="email">\
<span class="error" id="email_err">Email address not valid.</span>
//Other Form data
</form>
<div id="form-submit">Submit</div>
jQuery/Javascript
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
jQuery(document).ready(function($){
$('#form-submit').click(function(){
var email = $('#email').val();
if(!IsEmail(email)){
$('#email_err').show();
$('#email').focus();
}else{
$('#profile').submit();
}
});
}
Now all I want it to do is catch the email validation. Actual form submittal and data writing I would like to handle as I have it set up now where the PHP for writing the data is on the current page (action=""). Originally, it was an actual form submit button but I wanted to try and validate the email without page refresh.
I figure my understanding of the submit() function might be off-point, as what I'm reading seems like it's just a listener for a form submit, but doesn't actually submit the form itself. Is this correct or do I just have a flub up somewhere?
Since you're just validating your form, you can simply return true or false if the form is valid or not.
Some variant of:
$("#profile").submit(function() {
var email = $('#email').val();
if (!IsEmail(email)) {
...
return false; // Form will not submit
}
...
return true; // Form will submit as usual
});
Make sure you use <input type="submit" /> since you're attaching directly to the submit event.
Related
I'm trying to create a super simple email validator by using a regular expression. I've checked out similar questions here on SO as well as looking up other solutions elsewhere, like W3resource. I'm not sure if I'm overlooking something or if I have something typed wrong. The problem I'm having is that whether I enter either a correct or incorrect email, nothing happens. Neither of my alerts are working and the page remains blank.
Here is my Javascript code.
function checkmail(inputText)
{
var emailregex = /^\w[-._\w]*\w#\w[._\w]*\w\.\w{2,8}$/;
if(inputText.value.match(emailregex)) {
alert("You have entered a valid email address!");
return true;
} else {
alert("You have entered an invalid email address!");
return false;
}
}
Here is my relevant HTML code.
<div class="mail">
<center>
<p>Please enter an email address.</p>
<form id="inputemail">
<input type='text' name='input'/>
<input type="submit" name="submit" value="Verify" onclick="checkmail(inputText)"/>
</form>
</center>
</div>
<script src="regexobj.js"></script>
</body>
</html>
You need to specify where to get the data from. In your code you have a function that defines a variable "inputText". In your code there is no data being sent to the function and the function fails to get the data and returns an error.
To fix this you need to specify the data that you want to get, for example:
function checkmail(){
var input = document.querySelector("input[name='input']");
var emailregex = /^\w[-._\w]*\w#\w[._\w]*\w\.\w{2,8}$/;
if(input.value.match(emailregex)) {
alert("You have entered a valid email address!");
return true;
} else {
alert("You have entered an invalid email address!");
return false;
}
}
In this example the function will search for an input field with the name of input. input.value will contain the data from the input field.
In your HTML file you need to change the button submit to
<input type="submit" name="submit" value="Verify" onclick="checkmail()"/>
I have tested the above code and it should work accordingly. I hope to have helped with your problem.
Edit:
When submitting the form the page will automatically reload, if you want to stay on the same page and just give an alert you could do the following changes in your HTML file:
Remove the onsubmit property on the Submit button
<input type="submit" name="submit" value="Verify"/>
Add the following onsubmit function to your form
onsubmit="event.preventDefault(); checkmail();"
When you submit the form, the form will first prevent the page from reloading and will then execute your function. When you click on the alert, the page will not reload and remove the values inserted in the form.
I want to validate my code with javaScript and determine if it is okay to submit to php.
If it is correct I want the form to not submit to the php file that I have in 'action'.
If it is inncorrect I do not want the form to submit to the php file, and I want to display an error message.
Right now the form uses "onsubmit="return Validate()"" to call the validation function which displays a message and returns false to stop the form action. The problem is that the form action does not get stopped, and still runs. For some reason when I click the submit button twice the php message gets displayed then the java script message gets displayed.
My html form:
<form action="<?= base_Url(); ?>index.php/Login/loginuser" onsubmit="return Validate();" method="post" name="Login" accept-charset= "utf-8" >
Username: <input type="text" name="Username" maxlength="21" />
<br><br>
Password: <input type="text" name ="password" maxlength="20" />
<br><br>
<input type = "submit" value = "Login" class = "loginbutton" />
</form>
My java script function.
function Validate() {
document.getElementById("errorMSG").innerHTML = "Validate ran...";
return false;
}
From what I read online when onsubmit="return Validate()" gets returned false the form is supposed to not run. Thought this was right but cant figure out why its not working.
EDIT: I am useing codeigniter to display the url, and for other purposes on the project.
EDIT2: This is still not working... When the onsubmit is changed too, onsubmit="false" the php will not be called. Which is expected. When changed to onsubmit="true", the php will be called. Which is expected.
When onsubmit="return Validate();" and the Validation() function on says "return false;". It will for as expected. Same with return true. But when code gets placed in the function the boolean does not appear to be returned. The code below will not stop the php file from running when the login name is empty.
function Validate() {
if (document.getElementsByName("Username")=="" )
{
document.getElementById("errorMSG").innerHTML = "Validate ran...";
return false;
}
else
{
return true;
}
}
I am testing with chrome and firefox. There are no error messages displayed in the console on google chrome. I am not familiar with the debug tool for fire fox but i see no error messages displayed either.
I am now going to change the jquery script line to an updated version, maybe it will help..
I am using code igniter with controllers, views, libraries...
Everything was working fine until i started with the javascript validation.
You should use return false only when mandatory fields are empty
function Validate() {
// check whether mandatory fileds have some value or not
// document.getElementsByName("Username") always returns an array and will be robust way to access value by index 0 iin array like - document.getElementsByName("Username")[0]
if(document.getElementsByName("Username")[0].value == "" || document.getElementsByName("password")[0].value)
{
document.getElementById("errorMSG").innerHTML = "All fields required";
return false;
}
return true;
}
Please try this one 100% work
onsubmit="myFunction();return false;"
1.It should be just "Validate()" for onsubmit, not "return Validate().
And use onclick instead of onsubmit
Try this
<input type = "submit" value = "Login" class = "loginbutton" onclick = "Validate()"/>
I wrote an HTML code in which i'm validating the text field for alphabetical value Regex=/^[a-zA-Z]*$/. Actually for invalid input I want that form should not get submitted.
Validation Code
function Validate() {
var fname=$("#fname").val();
if(!(fname.match(Regex)))
alert("Invalid First Name");
return false;
}
HTML Code
<input type="text" name="fname" id="fname" onblur="return Validate();"/>
What should I do, so that for invalid value form should not get submitted.
It looks like you have to return false in onsubmit handler. onblur just handles focus.
Try to change onblur -> onsubmit
Use the onsubmit event of the form element to return true when validation was ok or false if any field did not validate.
Here is a working example. It also demonstrates that you should not rely on client sided validation since nobody stops you from doing the get (or even post) request anyway by just typing in the url. You have been warned about the limitations of client sided validation so here is the code:
<html>
<head>
<script>
function Validate() {
var text = document.getElementById("fname").value;
// simple validation example
if (text != "secret") {
alert("you must enter the right secret string!");
return false;
}
// everything validated
return true;
}
</script>
</head>
<body>
<form name="myForm" method="get" onsubmit="return Validate();">
<input type="text" name="fname" id="fname"/>
</form>
</body>
</html>
I am developing a web application in which I have created a form and in the onSubmit event of the form I have called a java script function which will check for "Field must not left blank" condition if it is left blank the form must not be posted so I have written following code:
Jsp Page Form
<form action="Result.jsp" name="validityCheck" onsubmit="return fnCheckEmptyField();">
<input type="text" name="txtIIDN" id="txtIIDN" style="font-size:medium;" onkeypress="return fnKeyPress(event)"/>
<input type="submit" id="btnValidityCheck" value="Check Validity" />
</form>
Javascript code is as follows
<script>
function fnCheckEmptyField()
{
var strDomain= document.getElementsByName("txtIIDN").value;
if(strDomain == null)
{
document.getElementById("lblValidityStatus").innerHTML="";
document.getElementById("lblValidityStatus").innerHTML="Domain Name Field Can't be Left Blank";
return false;
}
else
{
return true;
}
}
</script>
When I try to submit the form the javascript function gets executed and then form will gets posted whether the return value is true or false.
I dont want to submit the form when the return value is false i.e when field is empty
and also the condition in onsubmit event onsubmit="return fnCheckEmptyField(); showing me an error
Cannot return from outside a function or method.
Can you figure out what is the mistake I am commiting and possible solution for that?
Remove the onsubmit event on the form and In the submit button HTML, put this
<input type="submit" id="btnValidityCheck" value="Check Validity" onclick="return fnCheckEmptyField();" />
Adding on to what Furqan said, you should probably use the button and an onclick event to check the form, and if the form is valid, then call .submit() on your form.
I tend to not even use a submit button, I just have a normal button, and have it run javascript... then the javascript submits the form.
Example (HTML submit button):
<button id="btnValidityCheck" value="Check Validity" onclick="return fnCheckEmptyField();">Click Here</button>
Javascript function:
function fnCheckEmptyField() {
var strDomain= document.getElementsByName("txtIIDN").value;
if(strDomain == "") {
document.getElementById("lblValidityStatus").innerHTML="Domain Name Field Can't be Left Blank";
}
else {
document.getElementById("myFormId").submit();
}
}
Notice that if the javascript feel that the form is valid, THEN it will submit your form. You need to define an id for your form tag for this to work.
Also, I changed the == null check to == ""... that may have been causing issues...
Cheers!
I have the typical HTML "contact me" page, i.e. name, e-mail address and message. Since I want to do input validation on the page itself using JavaScript, I can't use a submit button, otherwise, the attached JavaScript function would be ignored. At least that's how I understand it, CMIIW.
I tried to load the next page writing location = mail.php but it appears that the form parameters don't get passed to my PHP page this way.
How do I validate input in JavaScript and pass parameters to my PHP page when ok?
TIA
Steven
You can use a form with an onsubmit handler on it, that returns false if the validation failed. If the check is ok, return true and the form will submit normally.
You'd have a javascript function something like this:
function check_it_all() {
if (all_ok) {
return true;
} else {
return false;
}
}
And the form
<form action=..... onsubmit="return check_it_all();">
....
</form>
Use the onSubmit event. Attach it to your form and if it returns true then your form will be sent to the PHP page. Read more here.
You should still use the submit button to submit the form, that is the correct behavior.
Input validation should be done using the <FORM>'s onSubmit event.
It should look something like this:
<script>
function validate() {
var isFormValid = whatever; // validate form
return isFormValid;
}
</script>
<form action="your.php" method="POST" onSubmit="return validate()">
<!---fields--->
</form>
The function validate() returns a bool.
This will stop the submission if validate() returns false.
<input type="submit" onclick="return validate()" value="click" />
I am an aspx.net developer so I am used to putting the validation call on the button.
If possible can't you use a JavaScript library like Jquery? It probably would make your life alot easier and they have tons of plug-ins for validation.
Such as
http://bassistance.de/jquery-plugins/jquery-plugin-validation/