7

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?

Edward Loveall
  • 1,983
  • 1
  • 19
  • 34
  • What do you mean by programmatically like creating an element description programmatically using JQuery ? – BASEER HAIDER JAFRI Nov 21 '17 at 16:10
  • I don't know why it's not working but as a workaround you can do it manually, get the attribute and the length of the value and compare them – Ricardo Ribeiro Nov 21 '17 at 16:32
  • Another workaround would be to use a pattern, something like this: `pattern=".{20,}"` – Ricardo Ribeiro Nov 21 '17 at 16:33
  • @BASEERHAIDER I mean like setting the value without typing in the field. `field.value = "some text"` – Edward Loveall Nov 21 '17 at 17:44
  • @EdwardLoveall so you want something like that if you do something like this field.value = "some text" and your field has min length 5 so it should show an error. is that true ? – BASEER HAIDER JAFRI Nov 21 '17 at 18:11
  • @EdwardLoveall can you please provide some code so that I get some idea what actually you are looking for because I am not clear about your requirement. – BASEER HAIDER JAFRI Nov 21 '17 at 18:14
  • Right, I think the code above demonstrates it. You can play with it here: https://s.codepen.io/edwardloveall/debug/yPKVzW Open up the console and type in the code I have in the question line by line, and you'll see field validation be false even when there are less than 20 character in the input. – Edward Loveall Nov 21 '17 at 18:55

2 Answers2

1

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
Seth Jeffery
  • 1,110
  • 1
  • 8
  • 8
-2

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.

izanagi_1995
  • 94
  • 1
  • 8