HTML5表单验证-错误消息自定义 [英] HTML5 Form validation - error message customization
问题描述
我有一个带有这样输入的表单.
<input type="text" name="question" class="form-control" required="" minlength="4" maxlength="2" size="20" oninvalid="setCustomValidity('please enter something')">
现在,默认验证消息效果很好.但是我想为特定规则设置自定义消息.
即对于诸如required
minlength
maxlength
之类的规则,当每个规则失败时,我想提供特定于失败规则的自定义错误消息.
我已经尝试过oninvalid="setCustomValidity('please enter something')"
,但这会为每条规则设置该消息.
如何为特定规则指定自定义错误消息?
使用setCustomValidity
属性更改验证消息,并使用validity
属性查找验证错误的类型
validity:描述元素有效性状态的ValidityState对象.
在表单加载时,由于用户事件(例如按键,更改等),将为每个表单元素初始化并在每次验证时更新属性. 演示 https://jsfiddle.net/91kc2c9a/2/ 注意:由于某些未知的原因,电子邮件验证在上面的小提琴中无法正常运行,但在本地应能正常工作 有关ValidityState的更多信息此处 > I have a form with an input like this.
Now the default validation messages work great. But I want to set custom messages for specific rules. i.e. for rules like I have tried How can I specify custom error messages for specific rules? Use validity : A ValidityState object describing the validity state of the element. Upon form load Demo https://jsfiddle.net/91kc2c9a/2/ Note: For some unknown reason email validation is not working in the above fiddle but should work fine locally More on ValidityState here 这篇关于HTML5表单验证-错误消息自定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!<input type="text" name="question" class="form-control" required="" minlength="4" maxlength="2" size="20" oninvalid="setCustomValidity('please enter something')">
required
minlength
maxlength
when each fails I want to provide a custom error message specific to the rule that failed.oninvalid="setCustomValidity('please enter something')"
but that sets that message for every rule. setCustomValidity
property to change validation messages and validity
property to find type of validation error
validate
property is initialized for each form element and updated on every validation due to user events like keypress,change etc. Here you can find the possible valuesvar email = document.getElementById("mail");
if (email.validity.valueMissing) {
email.setCustomValidity("Don't be shy !");
}
else{
event.target.setCustomValidity("");
}
email.addEventListener("input", function (event) {
if (email.validity.valueMissing) {
event.target.setCustomValidity("Don't be shy !");
}
else{
event.target.setCustomValidity("");
}
});