当HTML5需要的输入模式不通过时,如何创建自定义消息? [英] How can I create a custom message when an HTML5 required input pattern does not pass?
本文介绍了当HTML5需要的输入模式不通过时,如何创建自定义消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下内容:
I have the following:
<input required pattern=".{6,}" class="big medium-margin" name="Password" placeholder="Password" size="25" type="password" />
当我输入一个字符时,我收到一条消息:
When I enter just one character I get a message saying:
"Please match the requested format"
有没有一种方法可以将此消息自定义为请输入至少5个字符
Is there a way I can customize this message to say something like "Please enter at least 5 characters"
推荐答案
使用: setCustomValidity
代码:
Code:
$(function(){
$("input[name=Password]")[0].oninvalid = function () {
this.setCustomValidity("Please enter at least 5 characters.");
this.setCustomValidity("");
};
});
JSFiddle: http: //jsfiddle.net/yT3w3/
JSFiddle: http://jsfiddle.net/yT3w3/
非JQuery解决方案:
Non-JQuery solution:
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/
JSFiddle: http://jsfiddle.net/yT3w3/2/
这篇关于当HTML5需要的输入模式不通过时,如何创建自定义消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文