'Setting value of input with javascript dont pass "has-error" validation

I am trying to simulate a login using pure javascript, but I have an issue when I try to set the values,

I am using this function to simulate the click event, and it works, it changes the value that is displayed

var input = document.querySelectorAll("input")[1];
input.focus(); // you can also use input.focus()
input.click();
input.value="";

var text = "22399999999";
var l=text.length;
var current = 0;
var time = 100;


var write_text = function() {
  input.value+=text[current];
  if(current < l-1) {
    current++;
    setTimeout(function(){write_text()},time);
  } else {
    input.setAttribute('value',input.value);
  }
}
setTimeout(function(){write_text()},time);

var input2 = document.querySelectorAll("input")[2];
input2.focus(); // you can also use input.focus()
input2.click();

input2.value="";

var text2 = "1111";
var l2=text2.length;
var current2 = 0; 


var write_text2 = function() {
  input2.value+=text[current2];
  if(current2 < l2-1) {
    current2++;
    setTimeout(function(){write_text2()},time);
  } else {
    input2.setAttribute('value',input2.value);
  }
}
setTimeout(function(){write_text2()},time);

but, that only makes than the required validation be fire. enter image description here

but, if I click and hit with the keyboard, the display text doesn't change the value of the element but the validation error pass.

enter image description here



Solution 1:[1]

You should dispatch a change event after you have updated the value.

setTimeout(function(){write_text()},time);

input.dispatchEvent(new Event('change'));

Then you can force the validation status to update.

input.reportValidity();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Besworks