0

How I can watching to change input value for validation form?

I have validation script for my form.

This function work normal, but it start always only after click. How I can watching when change input.val()

form# send - form
input(type = "text"
 data - validate = "name")
button(class = "form_btn")


function validator(el, validName) {
 var mask_name = /^[A-Za-z0-9 ]{3,20}$/;
 var el = el;

 if (validName == "name") {
  var el_val = $(el).val();
  if (mask_name.test(el_val)) {
   $(el).removeClass('error');
  } else {
   $(el).addClass('error');
  }
 }
});

function mainValidation() {

 if ($('#send-form')) {
  $('input').each(function() {
   var this_el = $(this);
   var validName = $(this).data("validate");

   validator(this_el, validName);
  });
 }
};

$('.form_btn').on('click', function(e) {
 e.preventDefault();
 mainValidation();
});
Sasi Kathimanda
  • 1,788
  • 3
  • 25
  • 47

3 Answers3

0

Simply set up an event handler for the input event of the input field in question.

 // You need to provide a selector that references the input field properly
 $('inputSelectorHere').on('input', mainValidation);

You could also wait until the user leaves the input field to do the validation by using the blur event:

 // You need to provide a selector that references the input field properly
 $('inputSelectorHere').on('blur', mainValidation);
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

You can bind to the input change event:

$('input').on('change', function() {
    var this_el = $(this);
    var validName =  $(this).data( "validate" );

    validator( this_el, validName );
});
daniel0mullins
  • 1,937
  • 5
  • 21
  • 45
0

Try:

('input').on('change', function() {
    mainValidation();
});

Now you are listening the changes on all the input fields. When a field change, it will call your function mainValidation().

Let me know. Cheers

  • Welcome to Stack Overflow. Your answer may be correct, but it is helpful if you can explain why this will work, as it becomes a permanent record which other people may read at some later date. See http://stackoverflow.com/help/how-to-answer for more details – Mikkel Feb 07 '17 at 22:03
  • Hi, thank you for your tip :) – Daniele De Matteo Feb 07 '17 at 22:08