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

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

I have the following:



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

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

    Let suppose we have HTML field:

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

    Just change the HTML as

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

    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.

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

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

    <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.');
        }
    }
    
    0 讨论(0)
提交回复
热议问题