Edel
Edel

Reputation: 1

Form validation using jquery and javascript codes

i am trying to validate my form for empty fields but i am not sure what code i should use can someone please direct me i have tried the following code but its not working

$("validate").submit(function(event){
    $(".offset2").each(function(index) {
       if ($(this).val() == 0) {
           $("#error").css({"display": "inline"}).text("Some of the fields are empty");
           event.preventDefault();
       }
    });
});

Upvotes: 0

Views: 83

Answers (6)

amhed
amhed

Reputation: 3659

@CodeMonkeyForHire suggested using a Plugin.

The most used one is jQueryValidation. It will let you write markup like this:

<input id="cname" name="name" minlength="2" type="text" required/>

And then on your submit button you make one single call to validate all elements inside the form:

$("#commentForm").validate();

There are many other frameworks like ParselyJs or ValidateJs that you can try out.

P.S. Google is your friend, always look for plugins (probably someone else had the same problem you did)

Upvotes: 0

powerbuoy
powerbuoy

Reputation: 12848

I would definitely recommend H5Validate http://ericleads.com/h5validate/

It allows you to use the proper HTML5 attributes for validation.

Upvotes: 0

Shahzeb Khan
Shahzeb Khan

Reputation: 3642

aren't you missing a "#" before "validate".

   $("#validate").submit(function(event){
        $(".offset2").each(function(index) {
           if ($(this).val() == 0) {
               $("#error").css({"display": "inline"}).text("Some of the fields are empty");
               event.preventDefault();
           }
        });
    }

);

http://api.jquery.com/submit/

Upvotes: 0

M.G.Manikandan
M.G.Manikandan

Reputation: 993

Check this

if ($(this).val().length == 0) { // .length is missing in your code
    // Show Error
}
// Or
if (!$(this).val()) { // Empty string is consider as false type in JavaScript 
    // Show Error
}

Upvotes: 1

CodeMonkeyForHire
CodeMonkeyForHire

Reputation: 362

Just use a plugin.... More flexibility as you grow.

Here's free one after 1 minute of google.

http://jqueryvalidation.org/

Upvotes: 1

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

$(function(){
    $("validate").submit(function(event){
        event.preventDefault();
        var status=true;
        $(".offset2").each(function(index) {
           if (!$(this).val()) {
               $("#error").css({"display": "inline"}).text("Some of the fields are empty");
               status=false;
           }
        });
        return status;
    });
});

Upvotes: 0

Related Questions