Html 为什么我的“oninvalid”属性让模式失败?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16867407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:58:47  来源:igfitidea点击:

Why does my "oninvalid" attribute let the pattern fail?

htmlinput

提问by Sliq

This little HTML5 password field works perfectly WITHOUT the oninvalid attribute (the pattern say: minimum 6 characters):

这个小的 HTML5 密码字段在没有 oninvalid 属性的情况下完美运行(模式说:最少 6 个字符):

<form>
    <input type="password" name="user_password_new" pattern=".{6,}" required />      
    <input type="submit"  name="register" value="Register" />
</form>

See the jsFiddle here.

这里查看 jsFiddle 。

But when I add an oninvalid attribute that gives out a custom error message when user's input does not fit the pattern, the entire field NEVER becomes valid, see the code here:

但是,当我添加一个 oninvalid 属性时,该属性会在用户输入不符合模式时发出自定义错误消息,整个字段永远不会变为有效,请参阅此处的代码:

<form>
    <input type="password" name="user_password_new" pattern=".{6,}" oninvalid="setCustomValidity('Minimum length is 6 characters')" required />      
    <input type="submit"  name="register" value="Register" />
</form>

See the jsFiddle here.

这里查看 jsFiddle 。

Can you spot the mistake ?

你能发现错误吗?

回答by robertc

If you set a value with setCustomValidity()then the field is invalid. That is setting a non-zero length string causes the browser to consider the field invalid. In order to allow for the effects of any other validations you have to clear the custom validity:

如果您设置了一个值,setCustomValidity()则该字段无效。也就是说,设置一个非零长度的字符串会导致浏览器认为该字段无效。为了允许任何其他验证的效果,您必须清除自定义有效性:

<input type="password" name="user_password_new" pattern=".{6,}" required
   oninvalid="setCustomValidity('Minimum length is 6 characters')" 
   oninput="setCustomValidity('')" />

回答by musicman

Since I stumbled on the same problem, here is my solution – tested and working with FF, Chrome, IE 10, Edge (Feb 2017).

由于我偶然发现了同样的问题,这是我的解决方案 - 测试并使用 FF、Chrome、IE 10、Edge(2017 年 2 月)。

<form>
<input pattern="1234" oninput="setCustomValidity(''); checkValidity(); setCustomValidity(validity.valid ? '' :'please enter 1234');">
<input type="email" required>
<input type="submit">
</form>

Explanation:

解释:

setCustomValidity('');removes the custom error string which otherwise would always result in an invalid field at the validation process.

setCustomValidity('');删除自定义错误字符串,否则在验证过程中总是会导致无效字段。

checkValidity();does a manual validation – the same as it is happening at the form submisson. The result is stored in validity.valid.

checkValidity();进行手动验证 - 与表单提交时发生的情况相同。结果存储在validity.valid.

The second setCustomValidity(validity.valid ? '' :'please enter 1234');now sets the error string according to the validation result. If the field is valid it needs to be empty, otherwise the custom error string can be set.

第二个setCustomValidity(validity.valid ? '' :'please enter 1234');现在根据验证结果设置错误字符串。如果该字段有效,则需要为空,否则可以设置自定义错误字符串。

回答by Anonimys

I like to use like this:

我喜欢这样使用:

<input type="email" name="Email" required oninvalid="setCustomValidity('ErrorMessage')"/>

And unplugged for all of valid input data

并拔下所有有效输入数据

UPD, one more thing for better work:

UPD,为了更好的工作还有一件事:

    $("input").attr("onblur", "setCustomValidity('')");
    $("input").attr("oninput", "setCustomValidity(' ')");

回答by Scott Jibben

Although the answers for this question had good information, they weren't sufficient for my needs. I need to display different messages depending on which validity rule failed. In the other examples, the same validation failure message is used for all valiation failures.

虽然这个问题的答案有很好的信息,但它们不足以满足我的需求。我需要根据失败的有效性规则显示不同的消息。在其他示例中,相同的验证失败消息用于所有验证失败。

The "validity" property of a form object holds the key to creating more than one validation failure message.

表单对象的“有效性”属性是创建多个验证失败消息的关键。

You can review all of the different "validity" property properties at this web site.

您可以在此网站上查看所有不同的“有效性”属性。

https://www.w3schools.com/js/js_validation_api.asp

https://www.w3schools.com/js/js_validation_api.asp

This example shows how to display two different validation messages. If you uncomment the console.log() line below you can watch the validity property change as you type in a field.

此示例显示如何显示两个不同的验证消息。如果您取消注释下面的 console.log() 行,您可以在输入字段时观察有效性属性的变化。

<label for="user_password_new">New Password:</label>
<input type="password" name="user_password_new" id="user_password_new"
    pattern=".{6,}"
    value=""
    required
    oninput="
        setCustomValidity('');
        checkValidity();
        // console.log(validity);
        if (validity.patternMismatch) {
            setCustomValidity('Please enter at least six characters.');
        }
        else if (validity.valueMissing) {
            setCustomValidity('This field is required.');
        }
        else if (validity.valid) {
            setCustomValidity('');
        }
        // allow default validation message to appear for other validation failures
    "
>

NOTE: Some validity checks are "type" specific. For example, the "rangeOverflow", "rangeUnderflow", and "stepMismatch" attributes get set if type uses them; type="number".

注意:某些有效性检查是特定于“类型”的。例如,“rangeOverflow”、“rangeUnderflow”和“stepMismatch”属性在 type 使用它们时被设置;类型=“数字”。

回答by usr4896260

You can use titleas long as you don't mind having 'You must use this format:'before your message. If you want a full custom message, the setCustomValidity()worked for me.

title只要您不介意'You must use this format:'在您的消息之前使用,您就可以使用。如果您想要完整的自定义消息,这setCustomValidity()对我有用。