问题描述
如果你想在chrome中设置setCustomValidity函数的有效性,则不设置消息。
If you want to set the validity with setCustomValidity function as bellow in chrome the message is not set.
<input type="text" id="username" required placeholder="Enter Name"
oninput="setCustomValidity('error')" />
正如您所看到的,如果您运行此你可以看到在chrome上该字段没有验证消息。
As you can see if you run this jsfiddle on Firefox and Chrome you can see that on chrome the field does not have validation message.
为了看到发生了什么事情,请访问firefox打开jsfiddle并输入内容。输入内容后点击外部并观察是否添加了红色边框并显示文本错误。
In order to see the that something is happening go to firefox open the jsfiddle and input something. After you input something click outside and observ that a red border is added and text "error" is displayed.
是否有针对Chrome的解决方法?
Is there a workaround for Chrome?
编辑:
我已记录。请随时关注此主题。
I have logged the bug on chromium. Please feel free to follow this thread.
推荐答案
对我来说这看起来像个错误。我尝试运行,在。同样,它适用于Firefox,但不适用于Chrome。
It looks like a bug to me. I tried running the example given in the spec, in a JS fiddle here. Again, it works with Firefox, but not with Chrome.
function check(input) {
if (input.value == "good" ||
input.value == "fine" ||
input.value == "tired") {
input.setCustomValidity('"' + input.value + '" is not a feeling.');
} else {
// input is fine -- reset the error message
input.setCustomValidity('');
}
}
<label>Feeling: <input name=f type="text" oninput="check(this)"></label>
解决方法可能是使用,并提供一个用于验证输入的正则表达式。
A workaround could be to use the pattern
attribute on the input and provide a regex to validate the input with.
我将使用规范中给出的示例。您可以在模式属性中设置正则表达式模式,并在title属性中设置错误消息:
I will use the example given in the spec for this. You can set the regex pattern in the pattern attribute, and error message in the title attribute:
<label>Feeling: <input name=f type="text" pattern="((?!(?:good|fine|tired)).+)" title="Input is not a feeling."></label>
有了这个,您可以使用伪选择器:无效
将红色边框(或其他任何内容)应用于输入:
With that, you can use pseudo selector :invalid
to apply a red border (or anything else) to the input:
input:invalid {
border-color: red;
}
input:invalid {
border-color: red;
}
<label>
Feeling:
<input name=f type="text" pattern="((?!(?:good|fine|tired)).+)" title="Input is not a feeling." value="good">
</label>
小提琴:
注意:这种方法的明显缺点是你不再能够使用Javascript进行验证 - 而且你将无法验证字段组合的值。
Note: The obvious disadvantage of this approach is that you are no longer being able to use Javascript for validation - and you won't be able to validate the values of a combination of fields.
这篇关于Javascript setCustomValidity在Chrome版本65上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!