以编程方式设置字段时如何触发最小长度验证?

问题描述 投票:0回答:3

我的表单内有一个字段,如下所示:

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

输入时,

minlength
验证效果很好。但是,如果以编程方式设置输入的值,则不会触发验证。

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

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

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

有解决方法吗?还是有计划的修复?难道是我用错了?

html forms validation
3个回答
1
投票

今天偶然发现了这个问题,您可以通过

pattern
验证来解决它:

<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

0
投票

可以设置自定义验证消息,CSS 会立即拾取该消息:

    // Browser ignores minlength check when updated programatically.
    // Calling checkValidaty() does not trigger the check, nor does dispatching
    // an input event on the element. So we have to use customValidity().
    function checkInputValidity(inputEl) {
        const required = inputEl.hasAttribute('required');
        const length = inputEl.value.length;
        const minlength = inputEl.getAttribute('minlength');
        if (required && minlength && length < minlength) {
            inputEl.setCustomValidity(`Please fill out this field, you require at least ${length - minlength} more characters.`);
        } else {
            inputEl.setCustomValidity('');
        }
    }

-2
投票

您可以使用强制验证过程

field.checkValidity();

参见 MSDN 关于 checkValidity() 的信息

此页面是关于选择的,但它当然对每个输入字段都有效。

编辑:我的错,这不起作用,你应该手动进行验证。

© www.soinside.com 2019 - 2024. All rights reserved.