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

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

I have the following:



        
8条回答
  •  清歌不尽
    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.

    
                                        ^^^^^^^^^^^^^^^^^^^^^
    
    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.');
        }
    }
    

提交回复
热议问题