Monday, January 13, 2014

Html5 & jQuery form validation and get all error at a time


Html code


<form method='post'>
    <ul class="errorMessages"></ul>
    <div class="one">
        <label for="name">Name:</label>
        <input id="name" type="text" required="required"/>
    </div>
    <div class="two">
        <label for="comments">Comments:</label>
        <textarea id="comments" required="required"></textarea>
    </div>
    <div class="three">
        <label for="roll">Name:</label>
        <input id="roll" type="text" required="required"/>
    </div>
    <div class="four">
        <label for="email">Email:</label>
        <input id="email" type="email" required="required"/>
    </div>
    <div class="five">
        <label>Group:</label>
        <input type='radio' name='group' required="required"/> Group 1
        <input type='radio' name='group' required="required"/> Group 2
        <input type='radio' name='group' required="required"/> Group 3
    </div>
    <div class="buttons">
        <button type="submit" class="submit">Submit</button>
        <button type="button">Check</button>
    </div>
</form>

jQuery code


var createAllErrors = function() {
    var form = $( this ), errorList = $( "ul.errorMessages", form);
    var showAllErrorMessages = function() {
        errorList.empty();
        
        // Find all invalid fields within the form.
        var invalidFields = form.find( ":invalid" ).each( function( index, node ) {
            // Find the field's corresponding label
            var label = $( "label[for=" + node.id + "] ").html();
            if(label === undefined) {
                label = "";
            }
            // Opera incorrectly does not fill the validationMessage property.
            var message = node.validationMessage || 'Invalid value.';
            errorList.append( "<li><span>" + label + "</span> " + message + "</li>" );
        });
        errorList.show();
        return errorList.find("li").size();
    };

    form.find("button[type='button']").click(function() {
        var errorLength = showAllErrorMessages();
        errorList.show().prepend( "<li><span>Total Errors: </span> " + errorLength + "</li>" );
        form.find( "button.submit").click();
    });
    
    // Support Safari
    form.on( "submit", function( event ) {
        if ( this.checkValidity && !this.checkValidity() ) {
            $( this ).find( ":invalid" ).first().focus();
            event.preventDefault();
        }
    });
};
$( "form" ).each( createAllErrors );

No comments:

Post a Comment