0

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();
       }
    });
});
1
  • 2
    If you want to test if a field is "empty" you should test against an empty string, not against 0. The == operator actually returns true for "" == 0 and for "0" == 0, but if the user actually types a 0 that's obviously not empty... Commented Jun 25, 2013 at 11:58

6 Answers 6

1

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

Here's free one after 1 minute of google.

http://jqueryvalidation.org/

Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

0

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;
    });
});

Comments

0

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/

Comments

0

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

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

Comments

0

@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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.