When I run the following script it will not validate past the email validation. I remove the email validation and it will continue. Any insights to what may be causing the problem?
vEmail = document.getElementById("xEmail").value;
// checks to see if email is formatted correctly
var atpos=vEmail.indexOf("#");
var dotpos=vEmail.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=z.length) {
document.forms['checkout_form'].elements['email'].focus();
alert("Please check your eMAIL ADDRESS. It doesn't appear correct.");
return false;
}
// *** check each field for SHIPPING values ***
vShipTo = document.getElementById("xShipTo").value;
if (vShipTo=="") {
document.forms['checkout_form'].elements['ship_to'].focus();
alert("No SHIP TO NAME entered");
return false;
}
Unless z is defined elsewhere, I think the error stems from z not being defined.
if (atpos<1 || dotpos<atpos+2 || dotpos+2>= (z.length) ) {
This would cause it to fail as if the two conditions are not met, the program will encounter a reference error and stop running. If z is removed, the program continues toward the end.
Edit:
Also, this code is running within a function right?
Correct this(z is undefined here)
if(atpos<1 || dotpos<atpos+2 || dotpos+2 >= z.length) {
to
if(atpos<1 || dotpos<atpos+2 || dotpos+2 >= vEmail.length) {
Here is a working snippet
checkMail();
function checkMail(){
vEmail = document.getElementById("xEmail").value;
// checks to see if email is formatted correctly
var atpos=vEmail.indexOf("#");
var dotpos=vEmail.lastIndexOf(".");
if(atpos<1 || dotpos<atpos+2 || dotpos+2 >= vEmail.length) {
document.forms['checkout_form'].elements['email'].focus();
alert("Please check your eMAIL ADDRESS. It doesn't appear correct.");
return false;
}
//return false;need to set true
}
<body>
<form name="checkout_form" id="checkout_form" action="">
Email:<br>
<input type="text" id="xEmail" name="email" value="#gmail.com">
<br>
<br><br>
<input type="submit" onclick="return checkMail();"value="Submit">
</form>
</body>
Using regular expressions is probably the best way You can use to validate email
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(String(email).toLowerCase());
}
vEmail = document.getElementById("xEmail").value;
// checks to see if email is formatted correctly
if (!validateEmail(vEmail)) {
document.forms['checkout_form'].elements['email'].focus();
alert("Please check your eMAIL ADDRESS. It doesn't appear correct.");
return false;
}
// *** check each field for SHIPPING values ***
vShipTo = document.getElementById("xShipTo").value;
if (vShipTo=="") {
document.forms['checkout_form'].elements['ship_to'].focus();
alert("No SHIP TO NAME entered");
return false;
}
Related
I have a form which lets the user to enter the email address twice. i need to validate that the email is like the regex and that the two emails match.
Something is wrong with my code. Please note that i am restricted to use javascript only. Thanks,
this is my javascript
function checkEmail(theForm) {
var re = /^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"+"[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$/i;
if (theForm.EMAIL_1.value != re) {
alert('invalid email address');
return false;
} else if (theForm.EMAIL_1.value != theForm.EMAIL_2.value) {
alert('Those emails don\'t match!');
return false;
} else {
return true;
}
}
Your issue your not actually performing a regex. Your just comparing a regex string to an email.
if(theForm.EMAIL_1.value != re) /// <--- wrong.
{
alert('invalid email address');
return false;
}
On errors, use Event.preventDefault(); to prevent the form submit
Check for email validity only on the first input value
Than check to string equality on both input fields
function checkEmail (event) {
const e1 = this.EMAIL_1.value;
const e2 = this.EMAIL_2.value;
//Email Regex from //stackoverflow.com/a/46181/383904
const re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
const isEmail = re.test( e1 );
const isMatch = e1 === e2;
if( !isEmail ){
event.preventDefault();
alert('Invalid email address');
}
else if ( !isMatch ){
event.preventDefault();
alert("Those emails don't match!");
}
}
document.querySelector("#theForm").addEventListener("submit", formSubmitHandler);
<form id="theForm">
Email address:<br>
<input name="EMAIL_1" type="text"><br>
Confirm Email address:<br>
<input name="EMAIL_2" type="text"><br>
<input type="submit">
</form>
Since you might have more forms where an email is required (Contact form, Login form, Newsletter form, etc etc...) for more modularity you could create a reusable function for validation and than a specific form submit handler separately:
/**
* #param {string} a Email address 1
* #param {string} b Email address 2
* #return {string} Error message
*/
function invalidEmails (a, b) {
a = a.trim();
b = b.trim();
if (!a || !b) return "Missing email";
// Email Regex from stackoverflow.com/a/46181/383904
const re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
const isEmail = re.test(a);
const isMatch = a === b;
if (!isEmail) return "Invalid email";
else if (!isMatch) return "Emails do not match";
}
// Handle your form here
function formSubmitHandler (evt) {
const is_emails_invalid = invalidEmails(this.EMAIL_1.value, this.EMAIL_2.value);
if (is_emails_invalid) {
evt.preventDefault(); // Prevent form submit
alert(is_emails_invalid); // Show error message
}
}
document.querySelector("#theForm").addEventListener("submit", formSubmitHandler);
<form id="theForm">
Email address:<br>
<input name="EMAIL_1" type="text"><br>
Confirm Email address:<br>
<input name="EMAIL_2" type="text"><br>
<input type="submit">
</form>
You cant compare the first value with a regex. You have to use a regexp object. For more information read at
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec
Try this below function to validate your email.
And after the validation, compare the 2nd email.
Please note that regex test method is used in the validateEmail method.
function validateEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}
The below should work perfectly!
function validateForm(theForm) {
if (theForm.Email_1.value != theForm.Email_2.value)
{
alert('Emails don\'t match!');
return false;
} else {
return true;
}
}
I am currently working on an Email form and have little experience with javascript but am close to accomplishing what I need but struggling at one point, spent hours trying everything I can find searching and figured someone on here would probably have my answer instantly.
I currently have 3 functions checking a box is filled, email is correct format and passwords match.
If I set each function to run on its own upon clicking submit they work perfectly for their own intended purpose, however I am having trouble working out how to make it so that all 3 functions are run upon hitting submit. My final attempt which seems closest is adding the validateForm function at the bottom of my scripts to run all scripts but this did not seem to work. Hopefully something small I am overlooking, appreciate any help.
HTML:
<form name="registerkeys" form action="form.php" method="post" onsubmit="return validateForm();">
First Name: <input type="text" name="first_name"><br>
Last Name: <input type="text" name="last_name"><br>
Email: <input type="text" name="email"><br>
Phone Number: <input type="text" name="phonenumber"><br>
Information on Key: <input type="text" name="keyinfo"><br>
Password: <input type="password" name="password" id="password"></label><br>
Verify Password: <input type="password" name="passwordverify" id="passwordverify"><br>
Password Hint: <input type="text" name="passwordhint"><br>
<textarea rows="5" name="message" cols="30" placeholder="Comments:"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
Javascript:
function validateFill(){
var x=document.forms["registerkeys"]["first_name"].value;
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
var x=document.forms["registerkeys"]["last_name"].value;
if (x==null || x=="") {
alert("Last name must be filled out");
return false;
}
var x=document.forms["registerkeys"]["phonenumber"].value;
if (x==null || x=="") {
alert("Phone number must be filled out");
return false;
}
var x=document.forms["registerkeys"]["keyinfo"].value;
if (x==null || x=="") {
alert("Key info must be filled out");
return false;
}
var x=document.forms["registerkeys"]["pass1"].value;
if (x==null || x=="") {
alert("Password must be filled out");
return false;
}
var x=document.forms["registerkeys"]["passwordhint"].value;
if (x==null || x=="") {
alert("Password hint must be filled out");
return false;
}
}
function validateEmail()
{
var x=document.forms["registerkeys"]["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;
}
}
function validatePassword(){
var password = document.getElementById("password").value;
var passwordverify = document.getElementById("passwordverify").value;
var ok = true;
if (password != passwordverify) {
alert("Passwords Do not match");
document.getElementById("password").style.borderColor = "#E34234";
document.getElementById("passwordverify").style.borderColor = "#E34234";
ok = false;
}
else {
alert("Passwords Match!!!");
}
return ok;
}
function validateForm(){
var a = validateFill();
var b = validateEmail();
var c = validatePassword();
return a && b && c;
}
Your validateFill() and validateEmail() function should return true at the end.
validateFill() only returns false if validation has not passed, but never true. You should add return true at the end of the function, outside of conditions.
validateEmail() returns false if email is invalid but you are missing the return true if email is valid.
Also, to prevent duplicate popups I suggest that you change your validateForm() to something like this:
function validateForm() {
var a = validateFill();
if (a) var b = validateEmail();
else var b = false;
if (a&&b) var c = validatePassword();
else var c = false;
return a && b && c;
}
So it only checks one function until it passes, and then checks the next.
validateFill() and validateEmail() should return true at the end (right now they return nothing if validation passed.
validatePassword() should return true instead of ok.
I have two scripts at the top of a form. The first one works perfectly and provides a client-end validation for email addresses. The second one doesn't work at all, (even if I change my onsubmit to JUST that function name). I'm sure I'm missing something totally obvious. I can set it up to server-end validation, but the API with the software I'm using totally nukes the form entries, so I'm trying to avoid that.
<script>
function validateForm()
{
var x = document.forms["form5"]["element_1"].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;
}
}
</script>
<script>
function validateMisc()
{
if (document.forms["form5"]["element_27"].value !== null &&
document.forms["form5"]["element_57"].value == null)
{
alert("Misc details are required if a value is entered for Misc Projects.");
return false;
}
}
</script>
Here is my form action command currently.
<form
action="<?php echo $_SERVER["PHP_SELF"]?>"
name="form5"
action="demo_form.asp"
onsubmit="return validateForm() && validateMisc();"
method="POST">
if inputs with name="element_27" and name="element_57" exist they will never be null. They could be empty string. .value === '' and .value !== ''
Change your form like
<form action="<?php echo $_SERVER["PHP_SELF"]?>" name="form5" action="demo_form.asp" onsubmit="return validateForm();" method="POST">
Then i would revise the javascript like:
<script>
function validateForm()
{
var x=document.forms["form5"]["element_1"].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;
}
else
{
//If the email is valid, lets call the other function
validateMisc()
}
}
</script>
<script>
function validateMisc()
{
if (document.forms["form5"]["element_27"].value !== null && document.forms["form5"]["element_57"].value == null)
{
alert("Misc details are required if a value is entered for Misc Projects.");
return false;
}
}
</script>
I personally didn't check the code, so it could not work. In this case, my apologizes
I have a form and currently I have a javascript code to validate my form to make sure that the user fills out every input. my form action includes:
onsubmit="return validateForm();"
Which is the javascript to make sure every field is filled out. If it makes any difference, here is my javascript code:
<script type="text/javascript">//
<![CDATA[function validateForm() {
var a=document.forms["myform"]["inf_field_FirstName"].value;
var b=document.forms["myform"]["inf_field_Email"].value;
var c=document.forms["myform"]["inf_field_Phone1"].value;
if (a==null || a=="" || a=="First Name Here")
{ alert("Please enter your First Name!");
return false; }
if (c==null || c==''|| c=="Enter Your Phone Here")
{ alert("Please insert your phone number!");
return false; }
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.myform.inf_field_Email.value.search(emailRegEx) == -1)
{ alert("Please enter a valid email address.");
return false; } }
// ]]>
</script>
However on the phone number field, defined at c, I want to add another script that will pop up if the user doesn't enter a phone number at least 9 digits long. I was thinking of adding a code like this
<script type="text/javascript">
function validate(){
var c=document.forms["myform"]
if (input.length<9){
alert("Please enter a real phone number")
return false
}else {
return true
}
}
</script>
However I don't know how to run both functions on submit. I am extremely new to javascript so excuse me if there's already a simple solution to this.
Thanks
Everything in quotes after onsubmit= is just javascript. You can make sure both functions return true by doing:
onsubmit="return validateForm() && validate();"
You could add it as another rule in that conditional. For example:
if (c==null || c==''|| c=="Enter Your Phone Here" || c.length < 9) {
alert("Please insert your phone number!");
return false;
}
It's probably best to refactor this code, but that's probably the fastest way to do what you need.
I hope I can explain this right I have two input fields that require a price to be entered into them in order for donation to go through and submit.
The problem that I am having is that I would like the validation process check to see if one of the two fields has a value if so then proceed to submit. If both fields are empty then alert.
This is what I have in place now after adding some of the input i received earlier today:
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt); return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(billing_name_first,"You must enter your first name to donate")==false)
{billing_name_first.focus();return false;}
else if (validate_required(billing_name_last,"You must enter your last name to donate")==false)
{billing_name_last.focus();return false;}
else if (validate_required(billing_address_street1,"You must enter your billing street address to donate")==false)
{billing_address_street1.focus();return false;}
else if (validate_required(billing_address_city,"You must enter your billing address city to donate")==false)
{billing_address_city.focus();return false;}
else if (validate_required(billing_address_state,"You must enter your billing address state to donate")==false)
{billing_address_state.focus();return false;}
else if (validate_required(billing_address_zip,"You must enter your billing address zip code to donate")==false)
{billing_address_zip.focus();return false;}
else if (validate_required(billing_address_country,"You must enter your billing address country to donate")==false)
{billing_address_country.focus();return false;}
else if (validate_required(donor_email,"You must enter your email address to donate")==false)
{donor_email.focus();return false;}
else if (validate_required(card_number,"You must enter your credit card number to donate")==false)
{card_number.focus();return false;}
else if (validate_required(card_cvv,"You must enter your credit card security code to donate")==false)
{card_cvv.focus();return false;}
else if (validate_required(input1,"Need to enter a donation amount to continue")==false && validate_required(input2, "Need to enter a donation amount to continue")==false)
{
input1.focus();
return false;
}
}
}
This works fine... other than the fact that I get a message that reads error undefined... which i click ok about 2 times then I get the correct alert and instead of allowing me to correct the problem in IE7 and IE8 the form just processes.
Thanks guys any help would do
Matt
If I am understanding correctly, you only want to do the alert if both of the inputs are empty. If that's the case here's a refactoring of your code that will handle that.
function validate_required(field)
{
with (field)
{
if (value==null||value=="")
{
return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(input1)==false && validate_required(input2)==false)
{
alert('Need a donation to continue');
input1.focus();
return false;
}
}
}
take the alert() out of your assessment function- you're trying to do too much at once. a function to determine if input is valid or not should do only that one thing.
determine the state of your inputs first and then do something like
var field1Pass = validate_required(input1);
var field2Pass = validate_required(input2);
if ( !(field1Pass && field2Pass) ) {
alert("Need a donation amount to continue");
// TODO: logic to determine which field to focus on
return false;
}
var msg = "Need a donation amount to continue";
function validate_required(value) {
if(isNaN(value) || value == null || value == "") {
return false;
}
return true;
}
function validate_form(thisform) {
var i1 = validate_required($(thisform.input1).val());
var i2 = validate_required($(thisform.input2).val());
if(!(i1 && i2)) {
alert(msg);
thisform.input2.focus();
return false;
}
}
Look at the jQuery validation plugin. With the plugin it would just be a matter setting up the rules properly. You could get fancier and replace the default messages if you want. Check out the examples.
<script type="text/javascript">
$(function() {
$('form').validate({
'input1': {
required: {
depends: function() { $('#input2').val() == '' }
}
}
});
});
</script>
This sets it up so that input1 is required if input2 is empty, which should be sufficient since if input1 has a value, you don't need input2 and if neither has a value, then it will show your message for input1.
<input type="text" name="input1" />
<input type="text" name="input2" />
Here's my take, with refocusing on the first field that failed:
<body>
<form action="#" onsubmit="return validate(this);">
<input type="text" name="val0" /><br />
<input type="text" name="val1" /><br />
<input type="submit" />
</form>
<script type="text/javascript">
function validate(form) {
var val0Elem = form.val0, val1Elem=form.val1, elementToFocus;
// check fields and save where it went wrong
if (!numeric(val0Elem.value)) {elementToFocus=val0Elem;}
else if (!numeric(val1Elem.value)) {elementToFocus=val1Elem;}
// if there is an element to focus now, some validation failed
if (elementToFocus) {
alert('Enter numbers in both fields, please.')
// using select() instead of focus to help user
// get rid of his crap entry :)
elementToFocus.select();
// ..and fail!
return false;
}
// Helper function, "if a string is numeric":
// 1: it is not 'falsy' (null, undefined or empty)
// 2: it is longer than 0 too (so that '0' can be accepted)
// 3: it passes check for numericality using the builtin function isNaN
function numeric(s) {return (s && s.length>0 && !isNaN(s));}
}
</script>
</body>