Thursday, May 30, 2013

JavaScript - Form Validation

JavaScript is frequently used in form validation before the request submitted to server. It saves bandwidth and time, and also greatly prompt user experience.

However, in some situation, you have to use server side validation
  • JavaScript is not available on the device
  • JavaScript is turned off by user
  • JavaScript is disabled by network administrator
But that is not our topic today. :)

So, how to validate a form with JavaScript?

Let us see how the form looks like
















Validation Code
function saveChanges() {
    var firstName = document.getElementById("firstName");
    var lastName = document.getElementById("lastName");
    var phoneNumber = document.getElementById("phoneNumber");
    var email = document.getElementById("email");
    var password = document.getElementById("password");

    var errMsg = "";

    if (firstName.value === "") {
     errMsg += "First Name is empty. \n";
     firstName.style.borderColor = "red";
    }

    if (lastName.value === "") {
     errMsg += "Last Name is empty. \n";
     lastName.style.borderColor = "red";
    }

    if (phoneNumber.value.length > 30) {
     errMsg += "Phone number is too long, maxium 30 characters. \n";
     phoneNumber.style.borderColor = "red";
    }
    
    if (!pattern.test(email.value)) {
     errMsg += "Not a valid email. \n";
     email.style.borderColor = "red";
    }

    if (password.value.length < 8) {
     errMsg += "Your password is too short, minimum 8 characters. \n";
     password.style.borderColor = "red";
    }

    if (!((password.value.match(/[a-z]/)) && (password.value.match(/[A-Z]/)))) {
     errMsg += "Your password should have both lower and uppercase characters. \n";
     password.style.borderColor = "red";
    }

    if (!password.value.match(/\d+/)) {
     errMsg += "Your password should have at least one number. \n";
     password.style.borderColor = "red";
    }

    if (!password.value.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/)) {
     errMsg += "Your password should have at least one special character. \n";
     password.style.borderColor = "red";
    }

    if (errMsg != "") {
     alert(errMsg);
     return false;
    }

    return true;
}

Email Pattern
//
var pattern = /^(([^<>()[\]\\.,;:\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,}))$/;
//

Example of Validation













The Form
   

Personal Information


No comments:

Post a Comment