Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger the minlength validation when field is set programmatically?

I have a field inside of a form like this:

<input type="text" minlength="20" name="description" id="description" />

When typed into, the minlength validation works great. But if the input's value is set programmatically the validation won't trigger.

var field = document.querySelector("#description");

// type a couple of character into the field
field.validity.tooShort;
// true

field.value = '';
field.validity.tooShort;
// false

Is there a workaround for this? Or a planned fix? Am I using it wrong?

like image 760
Edward Loveall Avatar asked Jun 02 '26 20:06

Edward Loveall


1 Answers

Stumbled across this today, you can work around it with pattern validation:

<input type="text" pattern="^.{20,}$" name="description" id="description" />

JS:

var field = document.querySelector("#description");
field.value = 'too short';
field.validity.patternMismatch;
// true

field.value = 'very very very very very very long';
field.validity.patternMismatch;
// false
like image 148
Seth Jeffery Avatar answered Jun 04 '26 12:06

Seth Jeffery