Conditional rules for HTML5 form validation

2019-06-16 17:11发布

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?

2条回答
别忘想泡老子
2楼-- · 2019-06-16 17:26

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

查看更多
霸刀☆藐视天下
3楼-- · 2019-06-16 17:29

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

查看更多
登录 后发表回答