JavaScript Validation form instance

Source: Internet
Author: User
Tags email string valid email address alphanumeric characters

JavaScript Validation form instance

If you are creating a responsive site that contains some input forms, you should verify user input data. If you have to verify the name, last name, Email, username, age, compression code, and other fields of a registry ticket, you do not need to send unnecessary responses to your server. Next you will learn how to use JavaScript to implement such a function.

What do we verify?

Let's start to create a form with multiple input fields so that we can provide more vivid examples. Create an HTML file named index.html. The Code is as follows:

 

 

 <Script src = validation. js> </script> Registration Form 

The entire HTML code is a registration form. We didn't make it very beautiful, because we only intend to use it for our purpose of verifying it. We give it a name called "Registration Form" and put some labels and input fields below in an unordered list, which includes: user id, password, name, address, zip code, e-mail, and so on. We also contain two selection boxes, sex and language, and a countries drop-down list (we only list five, not all countries) and a submit button. Now, we can verify the information obtained from these input boxes.

 

 

Verification function

Now we have a registry ticket to obtain information. Next we will write the function validation function. First, we create a name named "validation. javaScript "JavaScript file (or you can change it to any name you want, but it must be the same as your own name when you process it ).

User Id verification

The first field for verification is the user id. See the following function:

 

 

function validateUsername(fld) {    var error = ;    var illegalChars = /W/; // allow letters, numbers, and underscores    if (fld.value == ) {        fld.style.background = 'Yellow';        error = You didn't enter a username.;        alert(error);        return false;    } else if ((fld.value.length < 5) || (fld.value.length > 12)) {        fld.style.background = 'Yellow';        error = The username is the wrong length.;        alert(error);        return false;    } else if (illegalChars.test(fld.value)) {        fld.style.background = 'Yellow';        error = The username contains illegal characters.;        alert(error);        return false;    } else {        fld.style.background = 'White';    }    return true;}

With this function, you cannot leave a blank field. It can only contain letters, numbers, and underscores, but cannot have a forward or backward slash. If the field is blank, the length is less than 5 or more than 12 characters, and contains invalid characters, a warning is displayed.

Password Verification

The password is another field that must be verified. The check code is as follows:

 

 

function validatePassword(fld) {    var error = ;    var illegalChars = /[W_]/; // allow only letters and numbers     if (fld.value == ) {        fld.style.background = 'Yellow';        error = You didn't enter a password.;        alert(error);        return false;     } else if ((fld.value.length < 7) || (fld.value.length > 15)) {        error = The password is the wrong length. ;        fld.style.background = 'Yellow';        alert(error);        return false;     } else if (illegalChars.test(fld.value)) {        error = The password contains illegal characters.;        fld.style.background = 'Yellow';        alert(error);        return false;     } else if ( (fld.value.search(/[a-zA-Z]+/)==-1) || (fld.value.search(/[0-9]+/)==-1) ) {        error = The password must contain at least one numeral.;        fld.style.background = 'Yellow';        alert(error);        return false;     } else {        fld.style.background = 'White';    }   return true;}

 

At one time, only letters and numbers are allowed for this field (but this time there is no underline). If the field is empty, it contains invalid characters, or it does not contain at least one number, a warning is displayed.

Name Verification

Verify the users name. The Code is as follows:

 

 

function allLetter(uname){    var letters = /^[A-Za-z]+$/;    if(uname.value.match(letters))    {        return true;    }    else    {        alert('Username must have alphabet characters only');        return false;    }}

If the name is composed of only letters, the function returns true. Otherwise, a warning is displayed.

Address Verification

We use the following code to verify the address:

 

 

 

function alphanumeric(uadd){    var letters = /^[0-9a-zA-Z]+$/;    if(uadd.value.match(letters))    {        return true;    }    else    {        alert('User address must have alphanumeric characters only');        return false;    }}

If address only contains letters and numbers, a warning is displayed for this code snippet.

Country Verification

Because you have already provided a countries list to the user, the verification only involves selecting a country from the list, and the code will be written as follows:

 

 

 

function countryselect(ucountry){    if(ucountry.value == Default)    {        alert('Select your country from the list');        return false;    }    else    {        return true;    }}

If you select a default value, give it a warning.

ZIP code verification

The ZIP code can only be a number, so the following function prompts a warning: "ZIP code shocould have numeric characters only ":

 

 

function allnumeric(uzip){    var numbers = /^[0-9]+$/;    if(uzip.value.match(numbers))    {        return true;    }    else    {        alert('ZIP code must have numeric characters only');        return false;    }}

Email Verification

Email is one of the most useful input fields in the form together with the username and password fields. It is also one of the most frequently verified fields. See the following code:

 

 

 

function checkEmail() {    var email = document.getElementById('txtEmail');    var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;    if (!filter.test(email.value)) {    alert('Please provide a valid email address');    email.focus;    return false; }}

This function checks that the first part of an Email string must contain uppercase and lowercase letters and numbers, followed by the "@" symbol, followed by uppercase and lowercase letters and numbers, the next point contains 2 to 4 uppercase and lowercase letters and numbers. If the string is not in this structure, a warning is displayed that the Email is invalid.

Gender Verification

Gender input in the form is a single choice button that must be selected. The verification function is as follows:

 

 

function validgender(mgender,fgender){    x=0;    if(mgender.checked)    {        x++;    } if(fgender.checked){    x++;}    if(x==0)    {        alert('Select Male/Female');        return false;    }    else    {        alert('Form Successfully Submitted');        window.location.reload()        return true;}}

This function only ensures that the options are selected. Otherwise, a warning will pop up asking you to select a button. Verify the language by using the same function variables.

Master validator

All the above verification functions should be included in a single verification function called onSubmit.

This function is like this:

 

 

 

function formValidation(){    var uid = document.registration.userid;    var passid = document.registration.passid;    var uname = document.registration.username;    var uadd = document.registration.address;    var ucountry = document.registration.country;    var uzip = document.registration.zip;    var uemail = document.registration.email;    var mgender = document.registration.msex;    var fgender = document.registration.fsex;         if(validateUsername(uid,5,12))    {        if(validatePassword(passid,7,12))        {            if(allLetter(uname))            {                if(alphanumeric(uadd))                {                    if(countryselect(ucountry))                    {                        if(allnumeric(uzip))                        {                            if(ValidateEmail(uemail))                            {                                if(validgender(mgender,fgender))                                {                                }                            }                        }                    }                }            }        }    }    return false;}

Note that this master validator is triggered only when the submit button is clicked.

 

 
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.