Jonas
Jonas

Reputation: 588

Conditional rules for HTML5 form validation

I am wondering if it's possible to set an element "required" based on some other element state. For instance, say I have an input element that I want to be "required" if and only if the user checks a specific checkbox. First, is this possible to do it without the use of JavaScript? Second, if we use JavaScript, of course one could set up a rule / validation if the user checks that checkbox, but what about consistency regarding the default browser validation errors? Would it be "correct" to add the "required" attribute to the element once the checkbox is clicked? I don't see an alternative here. What are your thoughts on this one?

Upvotes: 11

Views: 7215

Answers (2)

Jocelyn LECOMTE
Jocelyn LECOMTE

Reputation: 895

You may use polyfills to emulate native validation when not available:
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills

Upvotes: 0

Jason Gennaro
Jason Gennaro

Reputation: 34855

I don't think you can do this without javascript.

With javascript, you could do this easily enough.

I would add the required attribute only after the checkbox is clicked.

In fact, I would make this a toggled piece, so that the user can uncheck and unrequire the input.

However, I would not rely on browser's implementation of the required attribute. Instead, I would create my own required notification using some CSS (highlighting, animation, displaying some words).

Upvotes: 5

Related Questions