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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19122886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:00:56  来源:igfitidea点击:

How can I create a custom message when an HTML5 required input pattern does not pass?

html

提问by

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"

Is there a way I can customize this message to say something like "Please enter at least 5 characters"

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

采纳答案by gp.

Use: setCustomValidity

用: setCustomValidity

First function sets custom error message:

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

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

Second function turns off custom message. Without this function custom error message won't turn off as the default message would:

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

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

P.S. you can use oninput for all input types that have a text input.

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

For input type="checkbox"you can use onclick to trigger when error should turnoff:

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

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

For input type="file"you should use change.

对于输入, type="file"您应该使用更改。

The rest of the code inside change function is to check whether the file input is not empty.

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

P.S. This empty file check is for one file only, feel free to use any file checking method you like as well as you can check whether the file type is to your likes.

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

Function for file input custom message handling:

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

$("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 form required attribute. Set custom validation message?

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

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

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

Non-JQuery solution:

非 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/

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

回答by OBV

You can do a quick and dirty way with this trick:

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

<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>

http://jsfiddle.net/44wSU/1/

http://jsfiddle.net/44wSU/1/

回答by x0x

I'd add another attribute oninvalid.

我会添加另一个属性oninvalid

oninvalid="setCustomValidity('Please enter at least 5 characters')"

oninvalid="setCustomValidity('Please enter at least 5 characters')"

<input required pattern=".{6,}" class="big medium-margin" name="Password" placeholder="Password" size="25" type="password" oninvalid="setCustomValidity('Please enter at least 5 characters')"/>

回答by santiago arizti

I found that, chrome at least, adds to the message the title of the input automatically, so no extra js is required, see this:

我发现,至少 chrome 会自动将输入的标题添加到消息中,因此不需要额外的 js,请参见:

enter image description here

在此处输入图片说明

the input looks like this:

输入如下所示:

<input type="text" title="Number with max 3 decimals" pattern="^\d+(\.\d{1,3})?$">

回答by rajausman haider

It is very simple without javascript or jQuery validation. We can achieve it by HTML5

它非常简单,无需 javascript 或 jQuery 验证。我们可以通过 HTML5 来实现

Let suppose we have HTML field:

假设我们有 HTML 字段:

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

Just change the HTML as

只需将 HTML 更改为

<input required pattern=".{6,}" class="big medium-margin" title="Please enter at least 5 characters." name="Password" placeholder="Password" size="25" type="password" />

If you observe, just add title = "Error message"

如果您观察,只需添加 title = "Error message"

Now whenever form will be post, the given messages will be appeared and we did not need JavaScript or jQuery check. This solution works for me.

现在,无论何时发布表单,都会显示给定的消息,我们不需要 JavaScript 或 jQuery 检查。这个解决方案对我有用。

回答by federico-t

You'd need to use the setCustomValidityfunction. The problem with this is that it'd only guarantee a custom message for users who have JavaScript enabled.

您需要使用该setCustomValidity功能。这样做的问题是它只能保证为启用了 JavaScript 的用户提供自定义消息。

<input required pattern=".{6,}" ... oninput="check(this)">
                                    ^^^^^^^^^^^^^^^^^^^^^

function check (input) {
    if (input.value.search(new RegExp(input.getAttribute('pattern'))) >= 0) {
        // Input is fine. Reset error message.
        input.setCustomValidity('');
    } else {
        input.setCustomValidity('Your custom message here.');
    }
}

回答by Shahab Ghannadzadeh

https://www.geeksforgeeks.org/form-required-attribute-with-a-custom-validation-message-in-html5/

https://www.geeksforgeeks.org/form-required-attribute-with-a-custom-validation-message-in-html5/

    <input id="gfg" type="number" min="101" max="999" required> 

    <button onclick="myFunction()">Try it</button> 


    <p id="geeks"></p> 

    <script> 
        function myFunction() { 
            var inpObj = document.getElementById("gfg"); 
            if (!inpObj.checkValidity()) { 
                document.getElementById("geeks") 
                        .innerHTML = inpObj.validationMessage; 
            } else { 
                document.getElementById("geeks") 
                        .innerHTML = "Input is ALL RIGHT"; 
            } 
        } 
    </script> 

回答by jsherk

I simply use oninvalidto set the custom validty error message and then use onchangeto reset the message so the form can submit.

我只是oninvalid用来设置自定义有效性错误消息,然后onchange用来重置消息以便表单可以提交。

<input type="number" oninvalid="this.setCustomValidity('Please enter an INTEGER')" onchange="this.setCustomValidity('')" name="integer-only" value="0" min="0" step="1">