Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

 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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top