My form is working fine in Firefox and IE. On calling onsubmit it calls js function and validates the code, and if validation is good, then it submits the form.
However, in chrome it is not doing validation, but simply submitting the form directly.
I am not sure why it is so, Did lot of search but in vain.
Any help will be great towards solving this issue.
Form Code:
<form name="myform" action="queryfeedback.php" method="post" onSubmit="return validateForm(myform);">
<label for="labelField_Name" id="idLabel_Name"></label>
<input type="text" name="nameField_Name" id="idField_Name" placeholder="Enter your name here"/>
<br />
<label for="labelField_EMail" id="idLabel_EMail"></label>
<input name="nameField_EMail" type="text" id="idField_EMail" placeholder="Enter your E-Mail address here" />
<br />
<label for="labelField_Message" id="idLabel_Message"></label>
<textarea name="nameField_Message" id="idField_Message" placeholder="Enter your message for us here"></textarea>
<br />
<input type="Submit" name="nameSubmit" id="idButton_Submit" value="Submit" alt="Submit Button"/>
</form>
Validation Code:
function validateForm(form)
{
alert(form.nameField_Name.value);
//alert(formValueEMail.value);
//alert(formValueMessage.value);
if(form.nameField_Name.value=='')
{
alert("Name field is required. Please fill it in.");
form.nameField_Name.focus();
form.nameField_Name.select();
return false;
}
if(form.nameField_Name.value=='Enter your name here')
{
alert("Name field is required. Please fill it in.");
form.nameField_Name.focus();
form.nameField_Name.select();
return false;
}
if(form.nameField_EMail.value=='')
{
alert("E-Mail Address field is required. Please fill it in.");
form.nameField_EMail.focus();
form.nameField_EMail.select();
return false;
}
if(form.nameField_EMail.value=='Enter your E-Mail address here')
{
alert("E-Mail Address field is required. Please fill it in.");
form.nameField_EMail.focus();
form.nameField_EMail.select();
return false;
}
//Checking for correct format of EMail address.
var x=document.forms["myform"]["nameField_EMail"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
if(form.nameField_Message.value=='')
{
alert("Message field is required. Please fill it in.");
form.nameField_Message.focus();
form.nameField_Message.select();
return false;
}
if(form.nameField_Message.value=='Enter your message for us here')
{
alert("Message field is required. Please fill it in.");
form.nameField_Message.focus();
form.nameField_Message.select();
return false;
}
return true;
Try passing in the event parameter and running event.preventDefault() so it stops submitting the form until it is validated.
You aren't closing your function 'validateForm' with }. Therefore it could be throwing an error.
Use onsubmit="return validateForm(this);" Note that attribute name is onsubmit with no camel case and argument is this
validateForm should be a global function.
working example: http://jsfiddle.net/qrZ8a/3/
Related
I am trying to create a form where people can add their email addresses to sign up to a mailing list. I am struggling to validate whether they actually entered an e-mail address or not with JavaScript.
Here is the HTML form:
<script type="text/javascript" src="validate-email.js"></script>
<form id="updateform" action='send.php' onsubmit="return validateForm();" method='post'>
<input type="email" name="emailaddress" placeholder="Your e-mail address"/>
<input type="submit" name="submit" value="Submit">
</form>
And here is the JavaScript file's contents:
function validateForm()
{
var x=document.forms["updateform"]["emailaddress"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid e-mail address to receive updates.");
return false;
}
}
What am I doing wrong? I am a complete beginner...
EDIT: Why is this down-voted? What did I do wrong? If you read my comments, this is a legitimate problem, and the solutions I searched on Stack Overflow do not meet my needs.
1) use jQuery or similar framework and plugins.
2) use type="email" attribute for input tag.
<input type="email" name="email">
Or validate custom:
// validate function
var isEmail = function(email){
return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/.test(email);
}
function validateForm(){
var email;
// ...
// get value from html stuff
// ...
if(!isEmail(email))
return alert('Email format fail! Please correct.')
// do something next...
// alert("That's it! Dude.");
}
Use the regular expression to validate the email.
use this regex to validate
var regex= '/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/';
Original Post is here
Edit!
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validateForm()
{
var email=document.forms["updateform"]["emailaddress"].value;
if (!validateEmail(email))
{
alert("Please enter a valid e-mail address to receive updates.");
return false;
}
}
I have a webpage where a user submits a form containing an email field and a confirm email field.
How do I check to make sure both of these fields equal the same thing?
<form>
Email: <input type="text" name="email"><br /><br />
Confirm Email: <input type="text" name="confirmemail"><br /><br /><br /><br />
<input type="submit" value="Submit">
</form>
With jQuery, but no error handling, I'd suggest:
$('form').on('submit', function() {
return $('input[name=email]').val() == $('input[name=confirmemail]').val();
});
Ridiculously simple JS Fiddle demo.
Easiest way would be to use Javascript as you can stop form submission before it goes to your php file. However it is still good practice to verify the data entered with the php file as well as there are some programs that will allow you to change data being submitted in a form after javascript checks are made.
<script>
function checkMatch() {
var email = document.getElementById('email').value;
var emailConfirm = document.getElementById('emailConfirm').value;
if (email != emailConfirm) {
alert("Email addresses are not the same.");
return false; //Returning 'false' will cancel form submission
} else {
/*
place the return true; at the end of the function if you do other
checking and just have if conditions and return them as false. If
one thing returns false the form submission is cancelled.
*/
return true;
}
}
</script>
And change your form to have onSubmit
<form method="post" action="submit_query.php" onSubmit="checkMatch()">
Add id's to your email inputs such as: email and emailConfirm. You can change them if you wish but just for an example I used those.
I am using javascript to validate a web form for submission to a database, I have coded the form and the validation, but it does not seem to work.
When the form is completed and it is valid it is meant to go to a success page in a separate HTML file, but if it is not valid, the text on the form turns red, a message box pops up and alerts the user that it is invalid. On Chrome and IE, it seems to display the error but go to the success page anyway. The Message Box does not come up either, i only see the text turning red before it goes to the success page.
I wanted to know how to fix this. I have searched on the Internet but found no solution.
I have a function called validateForm(), which is a series of if statements checking the if the fields are valid, and if they are not, a variable called 'result' is set to false, at the end, it sends the alert message and returns the variable 'result'.
The code for my submit button is here:
<input type="submit" name="submit" value="Submit" onclick="return validateForm();" />
The Success Page is set in the form code as an 'action'.
Here is my Validate Form :
function validateForm(){
var result = true;
var msg = "";
if(document.ExamEntry.name.value==""){
msg+="You must enter your Name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if(document.ExamEntry.subject.value==""){
msg+="You must enter the Subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if(document.ExamEntry.examNumber.value=="")
{
msg+="You must enter the Examination Number \n";
document.ExamEntry.examNumber.focus;
document.getElementById('examnumber').style.color="red";
result = false;
}
if(document.ExamEntry.examNumber.value.length!=4)
{
msg+="Your Examination Number must be 4 characters long \n";
document.ExamEntry.examNumber.focus;
document.getElementById('examnumber').style.color="red";
result = false;
}
var lvlmsg="";
for(var i=0; i < document.ExamEntry.level.length; i++)
{
if(document.ExamEntry.level[i].checked)
{
lvlmsg = document.ExamEntry.level[i].value;
break;
}
}
if(lvlmsg=="")
{
msg+="You Must Indicate Your Level";
result=false;
document.getElementById('radioButtons').style.color="red";
}
else
{
alert(lvlmsg);
}
if(msg==""){
return result;
}
else{
alert(msg);
return result;
}
}
I created a form without the radio buttons and changed the function call.
I think the mistake is here:
<form name="ExamEntry" method="POST">
<input type="text" id="name" name="name" />
<input type="text" id="subject" name="subject" />
<input type="text" id="examnumber" name="examNumber" />
<input type="submit" name="submit" value="Submit" onlick="return validateForm()" />
</form>
I changed the function call to onsubmit (because I think it's better practice) and return validateForm() to simply validateForm(). Why would you want the return statement? Doesn't make sense to me.
http://jsfiddle.net/rcsole/cqy7q/
There are other questions regarding validating email addresses with javascript. There are also questions regarding validating forms. However I cannot get my code to work, and cannot find a question to cover this particular issue.
Edit
I totally understand that in a live website, server side validation is vital. I also understand the value of sending email confirmation. (I actually have a site that has all these features). I know how to code spam checks in php.
In this instance I have been asked to validate the email input field. I have to conform to xhtml 1.0 strict, so cannot use the type "email", and I am not allowed to use server side scripts for this assignment. I cannot organise email confirmation, it has to be totally checked via javascript.
I hope this clarifies my question
I am trying to validate a form for two things.
To check that all fields have data.
To see if a valid email address is entered.
I am able to validate a form fields for data, but trying to incorporate the email check is a trouble for me.
It was giving alerts before, but incorrectly, now it is not being called at all (or at least that is how it is behaving).
Once I get this working I then need to focus on checking if the email addresses match. However this is an issue outside of this question.
I am only focused on validating this in javascript. I am not concerned about server side in this particular instance (another issue outside of this question). Thanks.
function Validate()
{
var inputs = [document.getElementById('fname'),_
document.getElementById('lname'), document.getElementById('email1'),_
document.getElementById('email2')];
for(var i = 0; i<inputs.length; i++)
{
if(inputs[i].value == '')
{
alert('Please complete all required fields.');
return false;
}
else if ((id =='email1' || 'email2') &&_
(inputs[i].value!= /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/ )){
alert('Please enter a valid email address.');
return false;
}
}
}
<form onsubmit="return Validate()" action="" method="post" id="contactForm" >
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="text" name="email1" id="email1" />
<input type="text" name="email2" id="email2"/>
<input type="submit" value="submit" name="submit" />
</form>
A side note - to format text that wraps, is it ok (for the purposes of posting a question, to add and underscore and create a new line for readability? In the actual text I have it doesn't have this! Please advise if there is a simpler way to format my code for posts. Thanks again.
Edit 2
It works when I comment out this:
/*else if ((id =='email1' || id=='email2') && (inputs[i].value!= /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/ )){
alert('Please enter a valid email address.');
return false;
}*/
So this helps with the trouble shooting.
I already see a syntax error there :
else if ((id =='email1' || 'email2')
should be
else if ((id =='email1' || id=='email2')
from where I see it.
Note also that entering a space in any field will also pass through the test : you should trim your field values when testing for empty ones.
finally, concerning validating the email, this is not how you use regex. Please read this post for a demonstration on how to validate an email in javascript+regex.
var a=document.getElementById('fname');
var b=document.getElementById('lname');
var c=document.getElementById('email1');
var d=document.getElementById('email12')
if(a==""||b==""||c==""||d=="")
{
alert('Please complete all required fields.');
return false;
}
The best thing to do with validating an email address is to send an email to the address. Regex just doesn't work for validating email addresses. You may be able to validate normal ones such as john.doe#email.com but there are other valid email addresses you will reject if you use regex
Check out Regexp recognition of email address hard?
AND: Using a regular expression to validate an email address
I worked out the solution to my problem as follows. I also have in here a check to see if emails match.
// JavaScript Document
//contact form function
function ValidateInputs(){
/*check that fields have data*/
// create array containing textbox elements
var inputs = [document.getElementById("fname"),_
document.getElementById("lname"), document.getElementById("message"),_
document.getElementById("email1"), document.getElementById("email2")];
for(var i = 0; i<inputs.length; i++){
// loop through each element to see if value is empty
if(inputs[i].value == ""){
alert("Please complete all fields.");
return false;
}
else if ((email1.value!="") && (ValidateEmail(email1)==false)){
return false;
}
else if ((email2.value!="") && (EmailCheck(email2)==false)){
return false;
}
}
}
function ValidateEmail(email1){
/*check for valid email format*/
var reg =/^.+#.+$/;
if (reg.test(email1.value)==false){
alert("Please enter a valid email address.");
return false;
}
}
function EmailCheck(email2){
var email1 = document.getElementById("email1");
var email2 = document.getElementById("email2");
if ((email2.value)!=(email1.value)){
alert("Emails addresses do not match.");
return false;
}
}
<form onsubmit="return ValidateInputs();" method="post" id="contactForm">
<input type="text" name="fname" id="fname" />
<input type="text" name="lname" id="lname" />
<input type="text" onblur="return ValidateEmail(this);" name="email1" id="email1" />
<input type="text" onblur="return EmailCheck(this);" name="email2" id="email2"/>
<input type="submit" value="submit" name="submit" />
</form>
I am able to check for empty field but how do I also check for the valid email checking regular expression? here is what I have so far
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
var y=document.forms["myForm"]["email"].value;
if (y==null || y=="")
{
alert("email must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname"><br>
email: <input type="text" name="email">
<br><br>
<input type="submit" value="Submit">
</form>
The fist thing you could do is use the HTML5 type="email" attribute., the browser will validate natively. But you must always have a fall-back.
Use (found here)
/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
as regualar expression: and do
var validEmailStyle = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
if(!validEmailStyle.test(document.forms["myForm"]["email"].value))
{
// the user is dumb and fill in an invalid email, show a help text
// or something like that
}
-
edit after valid comment of PeeHaa
You must not forget to also validate server side, if you are using PHP you can use preg_match with the same regexp
var pattern = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinput))
{
alert('not a valid e-mail address');
}
Just showing an example, you can find a better regex pattern.