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

Viewed 1286

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?

2 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

You can force the validation process by using

field.checkValidity();

See MSDN about checkValidity()

This page is about select but it's of course valid for every input field.

EDIT : My bad, this is not working, you should do the validation manually.

Related