8

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.

1 Answer 1

12

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>

Sign up to request clarification or add additional context in comments.

1 Comment

The inputs need the attribute required to be considered for validation on submit. As was, all the inputs were css input:valid, and the forms could be submitted with two empty string values, regardless of any pattern specified.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.