Javascript setCustomValidity does not work on Chrome Version 65

前端 未结 1 1264
梦谈多话
梦谈多话 2021-01-21 08:09

If you want to set the validity with setCustomValidity function as bellow in chrome the message is not set.



        
1条回答
  •  隐瞒了意图╮
    2021-01-21 08:24

    It looks like a bug to me. I tried running the example given in the spec, in a JS fiddle here. Again, it works with Firefox, but not with Chrome.

    function check(input) {
      
      if (input.value == "good" ||
        input.value == "fine" ||
        input.value == "tired") {
        input.setCustomValidity('"' + input.value + '" is not a feeling.');
      } else {
        // input is fine -- reset the error message
        input.setCustomValidity('');
      }
    }


    A workaround could be to use the pattern attribute on the input and provide a regex to validate the input with.

    I will use the example given in the spec for this. You can set the regex pattern in the pattern attribute, and error message in the title attribute:

    
    

    With that, you can use pseudo selector :invalid to apply a red border (or anything else) to the input:

    input:invalid {
      border-color: red;
    }
    

    input:invalid {
      border-color: red;
    }

    Fiddle: https://jsfiddle.net/065thz0w/21/


    Note: The obvious disadvantage of this approach is that you are no longer being able to use Javascript for validation - and you won't be able to validate the values of a combination of fields.

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