Jquery Form Validation - Checking Fields

< Back to blog | Add a comment

Posted: 8th Apr 2009
Categories: Web Development Tips and Tricks
Tags: jquery form validation check forms fields

TECHY WARNING: Warning this post has 'techy-talk' be warned.

We thought we would share a cool way of checking form fields in Jquery. Just set the submitButton and the requiredFields variables and you are on your way. It is really useful for for validating a form before sending the data to the server (and you should always check before AND after sending the form don't forget!). This could be made in to an even neater, packed function if I had time, maybe later.

Have a play...

And the code is below for you...

<script type="text/javascript">
// below is where you would put the ID of the submit button
var submitButton = 'input#submit';

// below is where you would the required fields in your form separated by commas
var requiredFields = 'input#field1, input#field2';

// begin function
$(function(){
    $(submitButton).click(function(){
        var success = true;
        $(requiredFields).each(function(){
            if (!$(this).val()) {
                $(this).addClass('error').prev('label').addClass('error');
                $(this).focus(function(){
                    $(this).removeClass('error').prev('label').removeClass('error');
                });
                success = false;
            }
        });
        return success;
    });
});
</script>

<style type="text/css">
label.error { color: red; }
input.field { padding: 5px; border: 1px solid #ccc; }
input.error { color: red; border: 1px solid red; }
</style>

<p><label for="field1">Field one</label><input type="text" id="field1" class="field" /></p>
<p><label for="field2">Field two</label><input type="text" id="field2" class="field" /></p>
<p><input type="button" value="Check fields!" id="submit" /></p>

Add a comment









Back to top