Organizational Research By

Surprising Reserch Topic

Best way to validate fields and radio buttons with jquery?


I have several text input fields in my page, and few radio buttons. Now I need to validate them at client side, before I send them to server side (having server side validation too).

I am validating text inputs using jquery and javascript, but now I am wondering is this really the best way to validate them?

And how is this going to work with radio buttons?

$('form').submit(function() {
    validateForm($(this))
    return false;
});

function validateForm(form) {
    var FirstName=form.find('[name=FirstName]').val();
    if (!FirstName) {
        alert('Etunimi puuttuu');
        return false;
    }
}

asked May 8, 2015 in JAVASCRIPT by rajesh
0 votes
6 views



Related Hot Questions

1 Answer

0 votes

If you are just validating to ensure the fields aren't blank then i would add a class to all text fields like so

 type="text" id="Firstname" class="validate" />

then use Jquery to loop over all fields with a class of .validate and check whether any of them are blank. You can then choose how you alert the user.

$('.validate').each(function(){

   if($(this).val().length === 0)
   {
      alert($(this).attr('id')+ " is blank");
   }
});

for radio buttons you could check like so

if($('#myRadio').not(':checked'))
{
   alert('Radio not checked');
}

by testing the :checked pseudo selector

Or similarly grouping sets of checkboxes together by assigning a class and then looping over them to test that at least one has been checked.

answered May 8, 2015 by rajesh

...