Displaying 'Please fill out this field' for all empty and required fields

后端 未结 2 1240
夕颜
夕颜 2020-12-22 07:51

Is it possible to have a HTML/PHP page display multiple instances of the default \'Please fill out this field\' message? As in, right next to / underneath every required fie

相关标签:
2条回答
  • 2020-12-22 08:11

    You will need to create your own JS validation for every field and display the necessary response.

    This is how I would test if a field is not empty:

    function checkName(val){
            if(/^[^-\s][\w\s]+$/.test(val)){
                return true;
            }else{
                if(val.length != 0){
                    return false;
                }
            }
        }
    
    0 讨论(0)
  • 2020-12-22 08:14

    It looks like the link you posted showcases the use of reportValidity. Bear in mind, it's not supported in some browsers.

    var formElement = document.querySelector('#the-form');
    formElement.reportValidity();
    

    Since reportValidity might fail (if not implemented in the browser) you could just make a quick and dirty check:

    if (formElement.reportValidity) //check that the function exists on the form object
        formElement.reportValidity()
    

    This relies on the input elements having html5 validation attributes like <input type="text" minlength=4 required>.

    If you want a more complete validation flow, you will have to write a much more complex piece of software or re-use an existing solution.

    0 讨论(0)
提交回复
热议问题