A
A
Alexander2021-03-30 14:38:09
AJAX
Alexander, 2021-03-30 14:38:09

How to make ajax validate a field before submitting a form?

I want to make a validateField function that will send the field value to the server by Ajax and receive a true or false response

. How can I attach this function to the form submit event?

I would like to make these functionals independent of each other.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WebEagle, 2021-03-30
@idruweb

<input name="test1" class="js-validate" data-validate-name="validate1" />
<input name="test2" class="js-validate" data-validate-name="validate2" />

and connect the onchange handler
document.querySelectorAll('.js-validate').forEach(function(item) {
  item.addEventListener('onchange', function(event){
    // event.target - измененный элемент
    // event.target.value
    // event.target.getAttribete('data-validate-name') - какую валидацию вы хотите
    // тут вызывать Ajax запрос с требуемыми параметрами, когда придёт ответ
  });
});

When a negative response comes in, add an error class or attribute. For example js-input-error. If it returns true - delete the class
Next, when there is onSubmit of the form, validate so that there are no elements with this class or attribute

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question