Conditional rules for HTML5 form validation

2019-06-16 16:42发布

问题:

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?

回答1:

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).



回答2:

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