Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript setCustomValidity does not work on Chrome Version 65

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

<input type="text" id="username" required placeholder="Enter Name"
oninput="setCustomValidity('error')"  />

As you can see if you run this jsfiddle on Firefox and Chrome you can see that on chrome the field does not have validation message.

In order to see the that something is happening go to firefox open the jsfiddle and input something. After you input something click outside and observ that a red border is added and text "error" is displayed.

Is there a workaround for Chrome?

Edit: I have logged the bug on chromium. Please feel free to follow this thread.

like image 649
Radu Avatar asked Jul 21 '26 03:07

Radu


1 Answers

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('');
  }
}
<label>Feeling: <input name=f type="text" oninput="check(this)"></label>

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:

<label>Feeling: <input name=f type="text" pattern="((?!(?:good|fine|tired)).+)" title="Input is not a feeling."></label>

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;
}
<label>
  Feeling:
  <input name=f type="text" pattern="((?!(?:good|fine|tired)).+)" title="Input is not a feeling." value="good">
</label>

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.

like image 119
Nisarg Shah Avatar answered Jul 23 '26 17:07

Nisarg Shah