VaTo
VaTo

Reputation: 3098

How to validate empty input boxes from a form in jQuery

I would like to validate every single item in my form so in case one is empty I would like to print an alert. So for that I'm using the form.serializeArray() to check for any input box that could be empty. but my code is not working. Am I doing it good?

Here's my jsfiddle code

Upvotes: 2

Views: 66

Answers (3)

Mindsers
Mindsers

Reputation: 662

You are calling page.find() instead of $('') for selecting your form.

Suggestion 1 :

To improve your code and don't repeat code uselessly you can change your code like that :

$("#myform").submit(function() {
    var formItems = $(this).serializeArray();

    formItems.forEach(function (i, v) {
      if (v.value == '' || v.value == null || typeof v.value == 'undefined') {
         window.alert("need to fill up all those fields");
      }
    });
});

Suggestion 2 :

To not make too many pop-up; you can specify the field who is empty.

$("#myform").submit(function() {
    var formItems = $(this).serializeArray();

    formItems.forEach(function (i, v) {
      if (v.value == '' || v.value == null || typeof v.value == 'undefined') {
         $('input[name="' + v.name + '"]').val("This field must not be empty");
      }
    });
});

Upvotes: 1

Tom Yates
Tom Yates

Reputation: 931

The .find() method searches for a specified text in the document and highlights the matches.

You can further simplify your code:

$( "#myform" ).submit(function( form ) {
    $(this).serializeArray().forEach(function (i, v) {
      if (v.value == '' || v.value == null || typeof v.value == 'undefined') {
        alert("need to fill up all those fields");
      }
    });
});

Upvotes: 1

webdeb
webdeb

Reputation: 13211

instead of var form = page.find(..); use var form = $(..);

modified.. http://jsfiddle.net/vqr22ebz/6/

But there is another problem, you are calling the alert for every empty field.

Upvotes: 1

Related Questions