当 HTML5 要求的输入模式未通过时,如何创建自定义消息?

新手上路,请多包涵

我有以下内容:

 <input required pattern=".{6,}" class="big medium-margin" name="Password" placeholder="Password" size="25" type="password" />

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

 "Please match the requested format"

有没有一种方法可以让我自定义此消息以说“请输入至少 5 个字符”之类的内容

原文由 user1679941 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 305
2 个回答

使用: setCustomValidity

第一个函数设置自定义错误消息:

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

第二个功能关闭自定义消息。如果没有此功能,自定义错误消息将不会像默认消息那样关闭:

 $(function(){
    $("input[name=Password]")[0].oninput= function () {
        this.setCustomValidity("");
    };
});

PS 您可以将 oninput 用于所有具有文本输入的输入类型。

对于输入 type="checkbox" 您可以使用 onclick 在错误关闭时触发:

 $(function(){
    $("input[name=CheckBox]")[0].onclick= function () {
        this.setCustomValidity("");
    };
});

对于输入 type="file" 你应该使用 change。

change 函数中的其余代码是检查文件输入是否不为空。

PS 此空文件检查仅针对一个文件,您可以随意使用您喜欢的任何文件检查方法,也可以检查文件类型是否符合您的喜好。

文件输入自定义消息处理函数:

 $("input[name=File]").change(function () {
    let file = $("input[name=File]")[0].files[0];
    if(this.files.length){
        this.setCustomValidity("");
    }
    else {
        this.setCustomValidity("You forgot to add your file...");
    }
    //this is for people who would like to know how to check file type
    function FileType(filename) {
        return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
    }
    if(FileType(file.name)!="pdf"||FileType(file.name)!="PDF"){
        this.setCustomValidity("Your file type has to be PDF");
    //this is for people who would like to check if file size meets requirements
    else if(file.size/1048576>2){
        // file.size divided by 1048576 makes file size units MB file.size to megabytes
        this.setCustomValidity("File hast to be less than 2MB");
    }
    else{
    this.setCustomValidity("");
    }
});//file input custom message handling function

HTML5 表单必需属性。设置自定义验证消息?

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/

原文由 gp. 发布,翻译遵循 CC BY-SA 4.0 许可协议

你可以用这个技巧做一个快速而肮脏的方法:

 <form>
 <label for="username">Username:</label><br/>
  <input id="username" type="text" pattern=".{6,}" autofocus required title="Please enter at least 5 characters">
  <input id="submit" type="submit" value="create">
</form>

原文由 OBV 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题