HTML5 Conditional Validation Rules

I am wondering if the element “required” can be set based on some other state of the element. For example, let's say I have an input element that I want to “require” if and only if the user checks a specific checkbox. Firstly, can this be done without using JavaScript? Secondly, if we use JavaScript, of course, we could set a rule / check if the user checks this check box, but what about consistency regarding default browser check errors? Would it be “right” to add the attribute “required” to the element after clicking on the checkbox? I do not see an alternative here. What do you think about this?

+6
source share
2 answers

I do not think you can do this without javascript.

With javascript, you can do this quite easily.

I would add the required attribute only after clicking on the checkbox.

In fact, I would do this toggled so that the user can withdraw and withdraw the request.

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

+3
source

You can use polyfills to emulate the built-in check if it is not available:
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills

0
source

Source: https://habr.com/ru/post/913268/


All Articles