Hi,
I'm new to javascript that i didn't learn in college. My form can validate the first name, last name, and address line 1, but cannot validate the phone number and e-mail address.

Can u help me to fix this?

<!DOCTYPE html> <html> <head> <title>Plain form</title> <script>
        function validateForm() {
            // First name
            var fn = document.forms["form1"]["firstName"].value;
            if (fn == null || fn == "") {
                alert("First name must be filled out");
                return false;
            }

            // Last name
            var ln = document.forms["form1"]["lastName"].value;
            if (ln == null || ln == "") {
                alert("Last name must be filled out");
                return false;
            }

            // Phone number
            var phoneno = /^\d{11}$/;  
            if((pNo.value.match(phoneno))  
            {  
                 return true;  
            }  
            else  
            {  
                alert("Invalid phone number! Digits only!");  
                return false;  
            }

            // E-mail address
            var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;  
            if(emailAdd.value.match(mailformat))  
            {  
                document.form1.emailAdd.focus();  
                return true;  
            }  
            else  
            {  
                alert("You have entered an invalid email address!");  
                document.form1.emailAdd.focus();  
                return false;  
            } 

            // Address Line 1
            var a1 = document.forms["form1"]["addLine1"].value;
            if (a1 == null || a1 == "") {
                alert("First name must be filled out");
                return false;
            }
        }
    </script> </head> <body> <p>Fill up all the details in this form below, then click Submit. Required fields are marked in asteriks.</p> <form id="form1" onsubmit="return validateForm()" method="post">

    First name: <input type="text" name="firstName">*<br>
    Last name:  <input type="text" name="lastName">*<br>
    Phone number: <input type="text" name="pNo" maxlength="11">*<br>
    E-mail address: <input type="text" name="emailAdd">*<br>
    Address Line 1: <input type="text" name="addLine1">*<br>
    Address Line 2: <input type="text" name="addLine2"><br> <input type="submit" value="Submit"> </form> </body> </html> 

Well.. the way you are doing it is requiring 11 digits exactly. This means you are expecing an area code that is in a "proper" format, being 1 first, then the area code, then the 7 digit number. Not all people do this, and this is doomed to be a frustrating experience for your users.

Since you are using javascript, you have a lot of things available to you to prevent non number entry into a text field. Look into key Events (onkeydown, in particular) and the associated keyCodes. You can simply eat the keystroke if the code does not map to a non-numeric entry. Now, for validation, you still have a few options. If you are insistent on doing regex, then you need to change your exact match of {11} to something more flexible. You can do something like /^\d{10,11}/ which will ask for a number that is 10 or 11 characters in length. Personally, if you're going to do regex like this, I think you should look for all formats (with and without dashes, and + for country code). You can find examples of this exact regex all over the internet.

Now, for a note on security, and a kind reminder to the development community at large - javascript (or client side) validation is not secure. Please remember that no matter what sort of validation checks you do in javascript, you will need to do the exact same ones on the server, or enforce type restrictions on you data, especially if it is being stored in a database.

also a note on this check (and similar)

            var fn = document.forms["form1"]["firstName"].value;
            if (fn == null || fn == "") {
                alert("First name must be filled out");
                return false;
            }

fn will never be "null." In fact, null is a special type in javascript, in that it it cannot be anything until you explicity initialize something as null. You are looking for "undefined." The proper, "javascriptian", way to do this is:

var form = document.forms["form1"];
if (!form)
    return false;

var fn = form["firstName"];
if (!fn || fn.value == "") {
alert("First name must be filled out");
return false;
}

This way, should your form not exist you will not throw an exception. If the firstName input does not exist, you also will not throw exception by looking for a method of "undefined." This protects you from errors in your code, and page failure from the JS engine just giving up.

Lastly, since you are doing regex for phone numbers and email, you may want to consider doing it for fn/ln as well, or at the very least do a String.replace on all white space in the string. The reason for this is right now " " (just a space) passes your check. Im not sure how worried you are about that, but it's a possibility.

Member Avatar for diafol

I find this site: http://www.regxlib.com/ extremely useful for regexes. Telephone numbers are a particular pain as RT points out. There are so many different ways that people insist on using - Country codes: +44 or 0044 etc. Sometimes extensions may be suffixed too.

In HTML5 you can validate this without JS. If you change input type text to input type tel and input type email. Use attribute pattern for vaidate input type tel e.g.

<input type="tel" pattern="^[0-9]{8}$" />

Input type email you can use without pattern

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.