Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you trigger custom HTML5 form errors with JavaScript?

If i have an input like <input type="text"> and i want to trigger a native error on the input, can you do that? Like (faux code) ele.triggerError('Error Message');

It would then look like:

error
(source: tylergaw.com)

But with a custom message and for it's own validation function. Needed for AJAX validations for example.

like image 297
Oscar Godson Avatar asked Dec 21 '11 23:12

Oscar Godson


People also ask

Does HTML5 have form validation?

Using HTML5, we can create a form with built in validation (i.e. no javascript required). Earlier, we were using JAVASCRIPT to control form validation.

What are the new types for form validation in HTML5?

HTML5 introduced a new HTML validation concept called constraint validation. HTML constraint validation is based on: Constraint validation HTML Input Attributes. Constraint validation CSS Pseudo Selectors.

Which are two HTML5 attributes that can be used to validate form data?

There are three categories of HTML5 form validation features: HTML attributes on <input> , <select> , and <textarea> elements. (From here on out, I will just refer to them all as <input> cause brevity) CSS pseudo selectors.


1 Answers

The only way to trigger the native error is to submit the form. Although you can set a custom message with setCustomValidity (as described in my answer here) and you can trigger the invalid event with checkValidity, this only provides hooks for you to create your own validation UI. Here's a simple example you can play around with to verify.

Note that if you submit the form with the submit() method that will bypass the validation API. But if you trigger the click event of the submit button that will work in Firefox and Opera, but not Chrome. I'd avoid doing it right now.

like image 58
robertc Avatar answered Sep 28 '22 06:09

robertc