HTML5表单验证-错误消息自定义 [英] HTML5 Form validation - error message customization

查看:164
本文介绍了HTML5表单验证-错误消息自定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有这样输入的表单.

 <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.

<input type="text" name="question" class="form-control" required="" minlength="4" maxlength="2" size="20" oninvalid="setCustomValidity('please enter something')">

Now the default validation messages work great. But I want to set custom messages for specific rules.

i.e. for rules like required minlength maxlength when each fails I want to provide a custom error message specific to the rule that failed.

I have tried oninvalid="setCustomValidity('please enter something')" but that sets that message for every rule.

How can I specify custom error messages for specific rules?

解决方案

Use setCustomValidity property to change validation messages and validity property to find type of validation error

validity : A ValidityState object describing the validity state of the element.

Upon form load 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 values

var 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("");
  }
});  

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆