2

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

1
  • If you are interested I found Parsley.js to be an incredibly simple and effective validation library built on jQuery. Commented Sep 13, 2015 at 21:06

3 Answers 3

1

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.

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

1 Comment

Thank you so much, I didn't realize that.
1

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

Comments

1

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

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.