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

前端 未结 8 619
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 04:08

I have the following:



        
相关标签:
8条回答
  • 2021-02-01 04:22

    I'd add another attribute oninvalid.

    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')"/>
    
    0 讨论(0)
  • 2021-02-01 04:31

    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/

    0 讨论(0)
  • 2021-02-01 04:36

    I simply use oninvalid to set the custom validty error message and then use onchange to reset the message so the form can submit.

    <input type="number" oninvalid="this.setCustomValidity('Please enter an INTEGER')" onchange="this.setCustomValidity('')" name="integer-only" value="0" min="0" step="1">
    
    0 讨论(0)
  • 2021-02-01 04:37

    Use: 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.

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

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

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

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

    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.

    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?

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

    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/

    0 讨论(0)
  • 2021-02-01 04:37

    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> 
    
    0 讨论(0)
  • 2021-02-01 04:38

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

    the input looks like this:

    <input type="text" title="Number with max 3 decimals" pattern="^\d+(\.\d{1,3})?$">
    
    0 讨论(0)
提交回复
热议问题