当HTML5所需的输入模式不通过时,如何创建自定义消息?

前端之家收集整理的这篇文章主要介绍了当HTML5所需的输入模式不通过时,如何创建自定义消息?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下几点:
<input required pattern=".{6,}" class="big medium-margin" name="Password" placeholder="Password" size="25" type="password" />

当我输入一个字符时,我会收到一条消息:

"Please match the requested format"

有没有办法我可以自定义这个消息,说“请输入至少5个字符”

解决方法

使用:setCustomValidity

码:

$(function(){
    $("input[name=Password]")[0].oninvalid = function () {
        this.setCustomValidity("Please enter at least 5 characters.");
        this.setCustomValidity("");
    };
});

HTML5 form required attribute. Set custom validation message?

JSFiddle:http://jsfiddle.net/yT3w3/

非JQuery解决方案:

function attachHandler(el,evtname,fn) {
    if (el.addEventListener) {
        el.addEventListener(evtname,fn.bind(el),false);
    } else if (el.attachEvent) {
        el.attachEvent('on' + evtname,fn.bind(el));
    }
}
attachHandler(window,"load",function(){
    var ele = document.querySelector("input[name=Password]");
     attachHandler(ele,"invalid",function () {
        this.setCustomValidity("Please enter at least 5 characters.");
        this.setCustomValidity("");
    });
});

JSFiddle:http://jsfiddle.net/yT3w3/2/

原文链接:https://www.f2er.com/html5/168684.html

猜你在找的HTML5相关文章