【问题标题】:HTML5 Form ValidationHTML5 表单验证
【发布时间】:2012-07-20 22:23:51
【问题描述】:

我有两个关于 HTML5 表单验证的主要问题。

1-我使用此代码更改输入的验证消息

$$('INPUT').each(function(input) 
{    
  input.oninvalid = function(event) 
  {
     event.target.setCustomValidity('');
     if (!event.target.validity.valid) event.target.setCustomValidity('Please Fill');
  };
}

这个方法有一个大问题。如果输入无效,则提交表单时,会附加一条错误消息。所以它不会验证新的输入。即使在更正并再次提交后,它也不会让表单被提交,因为消息仍然是附加的。所以 event.target.setCustomValidity('') 将删除消息并且表单需要再次提交。 修正后提交。

我找不到纠正这种行为的方法。

2-如何完全隐藏或禁用这些工具提示但仍使用表单验证。有时候想用css无效和有效的伪类,但是还是显示这些提示。

我在提交按钮上找到 formnovalidate,然后我可以在提交之前手动检查每个输入的 validity.valid。有更好的主意吗?

【问题讨论】:

  • 为什么不在下一个“更改”事件(甚至是“keyup”或任何其他交互)上清除“自定义有效性”标志?
  • 处理使用“setCustomValidity()”API 的结果。如果您在用户开始与表单交互时立即清除字符串,您将避免重复提交问题。
  • 我会测试它。你知道任何关于 HTML5 验证的好资源吗?我找到了一些,但大多数都是一般的。
  • MDN 页面很不错。这是一个简单的系统,我认为部分原因是它令人困惑。
  • 你能把你的代码放在一个 jsFiddle 里吗? This example 与您的代码基本相同,但不需要重复提交。

标签: javascript forms html validation css


【解决方案1】:

就问题1而言:

我有意见

<input name="VoucherCode"  id="VoucherCode"  type="text" pattern="(1[0-9]{9})|(2[0-9]{9})" value="">

并改进了默认消息

$("#VoucherCode").on("invalid", function (event) {
    event.target.setCustomValidity('The format of Voucher Code is not correct.')
});

但这与您遇到的问题相同:如果用户第一次尝试错误,正确的响应仍然显示无效模式消息。

我根据@Pointy 的建议解决了这个问题:

$("#VoucherCode").on("invalid", function (event) {
    event.target.setCustomValidity('The format of Voucher Code is not correct.')
}).bind('blur', function (event) {
    event.target.setCustomValidity('');                
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 2016-07-04
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多