Quantcast
Channel: using jQuery | jQuery tutorials & sample code » Featured
Viewing all articles
Browse latest Browse all 10

Using jQuery for form validation

$
0
0

Today we will be looking at using jQuery for some really easy form validation. We will be looking at the real basic here and keeping it real simple. Enjoy

First, lets make a form with a text field and a submit button:

    <form action="" class="ourform">
        <input type="text" class="password"/>
        <input type="submit" />
    </form>

Ok, so we have a form with a class of “ourform” which contains a textfield with a class of “password” and a submit button. Simple enough. Now for our magical jQuery:

    $(document).ready(function(){
        $('.ourform').submit(function(){
            var password = $('.password').val();
            if (password == ""){
                alert("please enter the password");
                return(false);
            }
        });
    });

Cool, so in our jQuery ready block we have our selector, which selects the element with the class “ourform”. We then have our submit event. This even t runs when the form that we have selected (“ourform”) is submitted. Inside our function we declare a variable called password which has a value equal to the value of the element form ((‘.password’).val();).

We then have an if statement which checks if our variable password (which is equal to the value of the element with the class “password” which is our text input) is blank. If it is we return an error, “please enter the password”. We also have a “return(false)” which prevents the form from submitting.

That’s it, incredibly simple no? Good. As always, here is the demo, and here is the source (in case your control and c buttons are broken). Enjoy!

Share


Viewing all articles
Browse latest Browse all 10

Trending Articles