Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Input Validation with Custom Message

I'm trying to validate two input boxes and display a custom error message using HTML5 browser validation.

  • First input should be at least 3 characters, no custom error.
  • Second input should be at least 4 characters, with custom error.

The validation doesn't seem to work with my second input, I'm always prompted with my custom error message. When I remove the oninvalid it works.

Where am I going wrong?

My HTML is below;

<form>
  <input type="text" placeholder="min 3" pattern=".{3,}">
  <input type="text" placeholder="min 4" oninvalid="this.setCustomValidity('Must be 4 Characters')" pattern=".{4,}">
  <input type="submit" value="Check"></input>
</form>

I'm sure it's something obvious.. any help is appreciated.

Here's a fiddle.

like image 777
TheOrdinaryGeek Avatar asked Aug 03 '18 14:08

TheOrdinaryGeek


1 Answers

You could use the oninput attribute to restore the validity of the form like this: oninput="setCustomValidity('')".

This has a side effect and it is that if you type an invalid input and submit the form and type again another invalid value immediately the default message is shown instead of the custom one until you click again the submit option.

(See this forked jsfiddle, or below working snippet)

<form>
  <input type="text" pattern=".{3,}" placeholder="min 3">
  <input type="text" placeholder="min 4" pattern=".{4,}" oninvalid="setCustomValidity('Must be 4 Characters')" oninput="setCustomValidity('')">
  <input type="submit" value="Check" />
</form>

Another option would be adding an inline text with title attribute. The text will be appended after the default error message (See below snippet)

<form>
  <input type="text" pattern=".{3,}" placeholder="min 3">
  <input type="text" placeholder="min 4" pattern=".{4,}" title="Must be 4 Characters">
  <input type="submit" value="Check" />
</form>
like image 61
lealceldeiro Avatar answered Oct 25 '22 02:10

lealceldeiro