Showing posts with label Namespace in JavaScript. Show all posts
Showing posts with label Namespace in JavaScript. Show all posts

Sunday, March 9, 2014

Form Validation Using Advance JavaScript

Client side form validation is an important aspect in web development. Most of the developers preferred to validate a form using server side coding, but it is not sensible to do so for better user experience. So it's good to have client-side validation, because the user gets quick feedback, and doesn't have to wait for a server round-trip. 

Given below a standard coding steps applying which a developer can validate a form with ease.


1. Copy the following code and paste it in your common JS file.


var validator = {
    regex : {
        hasText : /^.*[a-zA-Z].*$/,
        email : /^[a-zA-Z0-9]{1}([\.\-\_]{0,1}[a-zA-Z0-9]{1,}){0,}@[a-zA-Z0-9]{2,}([\.]{1}[a-zA-Z0-9]{2,}){1,}$/,
        number : /^[0-9]{1,}$/
    },
    empty : function ( value ) {
        if ( value !== undefined && value.length > 0 || value != "") {
            return true;
        }else{
            return false;
        }
    },
    equal : function ( value1, value2 ) {
        if ( value1 == value2 ) {
            return true;
        }else{
            return false;
        }
    },
    isEmail : function ( text ) {
        var result = this.regex.email.test( text );
        if ( result === true ){
            return true;
        }else{
            return false;
        }
    },
    isNumber : function ( value ) { //Reviews the content, NOT the type
        var result = this.regex.number.test( value );
        if ( result === true ){
            return true;
        }else{
            return false;
        }
    },
isZipcode : function ( value ) { 
var lengthValidate;
if ((value.length) === 5){
lengthValidate = true;
}else{
lengthValidate = false;
}
        var result = this.regex.number.test( value );
        if ( result === true && lengthValidate === true){
            return true;
        }else{
            return false;
        }
    },
isPhone : function ( value ) { 
var lengthValidate;
if ((value.length) === 10){
lengthValidate = true;
}else{
lengthValidate = false;
}
        var result = this.regex.number.test( value );
        if ( result === true && lengthValidate === true){
            return true;
        }else{
            return false;
        }
    },
    hasText : function ( text ) {
        var result = this.regex.number.test( text );
        if ( result === false && text != "-1" ){
            return true;
        }else{
            return false;
        }
    },
    validateField : function ( fieldName, validationType, required, errorTarget, equalTo ){
        var _self = this;
        $('[name="' + fieldName + '"]')
            .keyup(
            function() {
                validate();
            }
        )
            .blur(
            function() {
                validate();
            }
        )
            .change(
            function(){
                validate();
            }
        );
        return validate();
        function validate(){
            var input_value = $('[name="' + fieldName + '"]').val();
            var result_regex = false;
            var result_required = true;
            var equalResult = true;
            switch( validationType ){
                case 'email':
                    result_regex = _self.isEmail ( input_value );
                    break;
                case 'number':
                    result_regex = _self.isNumber ( input_value );
                    break;
                case 'text':
                    result_regex = _self.hasText ( input_value );
                    break;
case 'zipcode':
                    result_regex = _self.isZipcode ( input_value );
                    break;
case 'phone':
                    result_regex = _self.isPhone ( input_value );
                    break;
            }
            if ( required === true ) {
                result_required = _self.empty ( input_value );
            }
            if ( equalTo !== undefined ){
                var compareTo = $('[name="' + equalTo + '"]').val();
                equalResult = _self.equal( input_value, compareTo);
            }
            if ( result_required === true && result_regex === true && equalResult === true ){
                $(errorTarget).removeClass('error');
                return true;
            } else {
                $(errorTarget).addClass('error');
                return false;
            }
        }
    }
};

2. Create an object of the namespace "validator" as mentioned below.

var formValidation = validator;

3. Call the function "validateField" to validate the desired input field. The function will return true/false based on the input value


var resultEmail, resultEmailConfirm, resultName, resultState, resultAge;
resultEmail = formValidation.validateField('fieldEmail', 'email', true, '.lblEmail');
resultEmailConfirm = formValidation.validateField('fieldEmailConfirm', 'email', true, '.lblConfirmEmail', 'fieldEmail');
resultName = formValidation.validateField('fieldName', 'text', true, '.lblName');
resultState = formValidation.validateField('fieldState', 'text', true, '.lblState');
resultAge = formValidation.validateField('fieldAge', 'text', true, '.lblAge');


Code Explanation

formValidation.validateField('fieldEmail', 'email', true, '.lblEmail');
In the above statement:
formValidation : Namespace object
validateField : Namespace Method
fieldEmail : Input Field Name Attribute Value
email : Check Type for validateField Function
true : Mandatory Field Check
.lblEmail : Highlight Error Field Target


With Regards,
Animesh Nanda
Sr.Software Engineer | Photon Infotech
Bengaluru | Karnataka | INDIA.