1
\$\begingroup\$

Is this a good form validation script?

$(document).ready(function() {
 $("form").submit(function() {
 var shouldSubmit = true;
 $(this).children(":input:not(:button, [type=\"submit\"], [type=\"reset\"])").each(function() {
 if ($(this).val() == "")
 {
 shouldSubmit = false;
 return shouldSubmit;
 }
 });
 if ($("input:checkbox").length > 0)
 {
 if ($("input:checkbox:checked").length == 0)
 shouldSubmit = false;
 }
 if ($("input:radio").length > 0)
 {
 if ($("input:radio:checked").length == 0)
 shouldSubmit = false;
 }
 if (shouldSubmit == false)
 alert("All form fields must be filled out.");
 return shouldSubmit;
 });
});
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jul 16, 2013 at 16:08
\$\endgroup\$
1
  • \$\begingroup\$ Have a look at this method: api.jquery.com/is You can save some work by doing something like if($("input:radio").is("checked)). Also you can just return false right away instead of setting a boolean then returning false. \$\endgroup\$ Commented Jul 16, 2013 at 16:39

1 Answer 1

1
\$\begingroup\$

The if statements could be cleaner:

 if ($("input:checkbox").length > 0 && $("input:checkbox:checked").length == 0)
 {
 shouldSubmit = false;
 }
 if ($("input:radio").length > 0 && $("input:radio:checked").length == 0)
 {
 shouldSubmit = false;
 }
 if (!shouldSubmit)
 {
 alert("All form fields must be filled out.");
 }
answered Jul 16, 2013 at 18:56
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.