【问题标题】:HTML5 Validation: different behavior when custom validation message is setHTML5 验证:设置自定义验证消息时的不同行为
【发布时间】:2014-11-04 16:39:07
【问题描述】:

我一直在处理这个注册表单,我在其中使用 HTML5 的验证检查。为了在您不匹配所需的模式时显示自定义错误消息,我关注了这篇文章: How can I change or remove HTML5 form validation default error messages?

现在所有功能都可以正常工作,除了这个我无法解决的烦人问题:匹配模式时弹出气泡不会自动消失。为了进一步解释这个问题,我制作了这个 JSFiddle:http://jsfiddle.net/Jeroen88/Lujt490o/,代码如下:

<form>
<fieldset>
    <legend>Custom message</legend>
    <label for="password1">Password 1:</label>
    <input type="password" pattern=".{4,}" required id="password1"
        oninvalid="setCustomValidity('Password must be at least 4 characters')"
        onchange="try{setCustomValidity('')}catch(e){}" />
    <input type="submit" />
</fieldset>
</form>

如您所见,即使在模式匹配后,验证消息也会继续出现。 使用默认错误消息不会描述此行为!

<form>
<fieldset>
    <legend>Without custom message</legend>
    <label for="password2">Password 2:</label>
    <input type="password" pattern=".{4,}" required id="password2" />
    <input type="submit" />
</fieldset>
</form>

所以我的问题是:如何使自定义验证消息具有与默认消息相同的行为?

【问题讨论】:

  • 你试过this answer吗?
  • @bzlm 谢谢,我会试试这个。该演示似乎表现出正确的行为。
  • @bzlm 是的!有用!我已经测试了我的(更详细的)代码,结果发现只需将“onchange”更改为“oninput”就可以了!但知道为什么会这样吗?无论如何,非常感谢你。我应该如何将您的答案标记为解决方案?
  • 您回答自己是正确的。 :)

标签: javascript regex html validation


【解决方案1】:

通过将 'onchange' 更改为 'oninput' 并让自定义函数正确处理 setCustomValidity 解决了问题,就像 Rikin Patel 在 this answer to another question 中一样:

HTML:

<input type="text" pattern="[0-9]{10}" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);" />

JAVASCRIPT:

function InvalidMsg(textbox) {

     if(textbox.validity.patternMismatch){
        textbox.setCustomValidity('please enter 10 numeric value.');
    }    
    else {
        textbox.setCustomValidity('');
    }
    return true;
}

Fiddle Demo

【讨论】:

    猜你喜欢
    • 2012-11-27
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多