以编程方式设置字段时,如何触发最小长度验证? [英] 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" />
输入时, minlength
验证效果很好.但是,如果以编程方式设置输入的值,则不会触发验证.
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?
推荐答案
今天偶然发现了这个问题,您可以使用 pattern
验证来解决它:
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
这篇关于以编程方式设置字段时,如何触发最小长度验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文