Wednesday 3 July 2013

Javascript Validation

Validation

We will create JavaScript functions (one for each input field whose value is to validated) which checks whether a value submitted by user passes the validation. 

HTML Code of the Sample Registration Form

Name

Email

JavaScript code for validation



Name validation
 


Email Validation
 
    
    var email = document.registration.email.value;
    if (email == "") {
        document.getElementById("error2").innerHTML = "Enter email";
        return false;
    }else if (email != "") {
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (!filter.test(email)) {
            document.getElementById("error2").innerHTML = "Enter valid email address";
            document.registration.email.focus;
            return false;

        }
    } else {
        document.getElementById("error2").innerHTML = " ";
        return true;
    }

Phone No. Validation
 
    var phone = document.registration.phone_no.value;
    if (phone == "") {
        document.getElementById("error1").innerHTML = "Enter phone no";
        return false;
    } else if (isNaN(phone)) {
        document.getElementById("error1").innerHTML = "Phone_no should be integer";
        return false;
    } else if (phone.length != 10) {
        document.getElementById("error1").innerHTML = "Phone_no should be 10 digits";
        return false;
    } else {
        document.getElementById("error1").innerHTML = "";
        return true;
    }

Gender Validation

  
if(document.registration.malegender.checked){
 x++;
} 
if(document.registration.femalegender.checked){
  x++; 
}
if(x==0)
{
document.getElementById("error1").innerHTML = "";
return true;
}else{
document.getElementById("error1").innerHTML = "Select Gender";
return false;
}

Select Box Validation
 





No comments: