-2

I got an issue. I want to be able to validate data in multiple forms on my website with JQUERY in real time. For example, I have a "add customer" form, I want to be able to disable the Submit button until all the fields are validated. And validation has to occur in real time, meaning after every mouse move, key up key down, page load and all that other stuff. Another example is when I click on "Edit Customer" for one of my current customers. A Modal pops up with a form that has all current information already entered. The Submit button has to be active because all the fields are already validated. If I remove the first name for example, the Submit button has to get disabled. Validation occurs on many ways, I am using formance to validate phone numbers and emails.

Either way, I already got something working but it's buggy. I wanna know what the best way to go about doing this? Am I doing it right? Here's an example:

$(document).on('click focus focusin focusout hover keydown keypress keyup load', function() {
if ($("#customer-add-form input[name='phoneNumber']").formance('validate_phone_number') &&
    $("#customer-add-form input[name='email']").formance('validate_email') &&
    $("#customer-add-form input[name='zipCode']").formance('validate_number') &&
    $("#customer-add-form input[name='city']").val().length >= 2 && 
    $("#customer-add-form input[name='firstName']").val().length >= 2 && 
    $("#customer-add-form input[name='lastName']").val().length >= 2 && 
    $("#customer-add-form input[name='companyName']").val().length >= 2 && 
    $("#customer-add-form input[name='address']").val().length >= 2){
        $("#customer-add-form input[type='submit']").prop("disabled", false);
} else {
    $("#customer-add-form input[type='submit']").prop("disabled", true);
} 
}
1
  • 1
    There are validation libraries (along with HTML5 validation) that you can use. I'd say generally you can check them on change and focusout. Aug 31, 2015 at 21:43

1 Answer 1

2

I'd recommend that you not try to "reinvent the wheel".

This is a good jQuery form validation plugin: http://formvalidator.net/#reg-form

If you must roll your own then you would want to use something like:

$('input').on('change', function(){...});
3
  • 2
    Or .on('input', ..., if you want it real time. On change will only happen if you lose focus (click away): jsfiddle.net/L7vp6mu2
    – blex
    Aug 31, 2015 at 21:48
  • The answer is only for letting the user know if the field is validated or not. I need to also be able to disable and enable a button in real time. Depending on all fields in a form.
    – odannyc
    Aug 31, 2015 at 21:54
  • If you are monitoring each form field then just have a line that disables the button when it doesn't pass your validation test.
    – Derek
    Sep 1, 2015 at 11:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.