html5 oninvalid doesn't work after fixed the input field

前端 未结 5 1618
故里飘歌
故里飘歌 2020-12-06 01:08

I have this input code in my form:



        
相关标签:
5条回答
  • 2020-12-06 01:55

    The issue is that the custom validity error message needs to be reset to blank/empty again, or the field will never validate (even with correct data).

    I use oninvalid to set the custom validity error message, and then use onchange to set the message back to default (blank/empty), and then when the form is checked again it will correctly submit if data was corrected, or it will set the custom error message again if there is problem.

    So something like this:

    <input type="number" oninvalid="this.setCustomValidity('You need to enter an INTEGER in this field')" onchange="this.setCustomValidity('')" name="int-only" value="0" min="0" step="1">
    
    0 讨论(0)
  • 2020-12-06 01:58

    If you set a value with setCustomValidity() then the field is invalid. That is setting a non-zero length string causes the browser to consider the field invalid. In order to take effects of your new input you have to clear the custom validity. Simply you can use the following:

    <input required maxlength="255" id="information_name" minlength=1 name="information[name]" oninvalid="setCustomValidity('Should not be left empty.')" 
       oninput="setCustomValidity('')" />
    

    There is no need to use Javascript for this.

    0 讨论(0)
  • 2020-12-06 02:05

    You can set a custom validity message with setCustomValidity, however any non-blank string will cause the field to act as if it had an invalid value. You need to setCustomValidity('') to clear the invalidated state of the field.

    If your validity is simple and controlled via field attributes, you can use object.willValidate to do the test and set the custom validity message:

    oninvalid="this.setCustomValidity(this.willValidate?'':'your custom message')"

    0 讨论(0)
  • 2020-12-06 02:10

    If you setCustomValidity to any value that is not the empty string then that will cause the input to be in the invalid state. So your condition is checking for a value, then setting the field to be invalid either way. Only setCustomValidity when the value in the field is actually invalid, otherwise set it to an empty string:

    <script>
     function check(input) {
       if (input.value == "") {
         input.setCustomValidity('Debe completar este campo.');
       } else  {
         input.setCustomValidity('');
       }
     }
    </script>
    
    0 讨论(0)
  • 2020-12-06 02:13

    For me only oninvalid="this.setCustomValidity(this.willValidate ? '' :'You must choose the account type from the list')" works. There are lots of issues while using it with IE.

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