html5: Significance of attribute named required in checkbox/radio

前端 未结 4 720
暖寄归人
暖寄归人 2021-01-04 01:05

On form submission, how could you possibly mark a checkbox/radiobutton as required?

Source of inspiration: Pekka\'s answer to a question

4条回答
  •  生来不讨喜
    2021-01-04 01:37

    For checkboxes, the best way is probably to pre-select it and set it to disabled. Just kidding.

    To ensure one radio button in a group has been selected, either start with a default choice or validate using javascript. There are no HTML-ways to do that because every possible selection is valid.

    In html5 there is a required attribute for checkboxes.

    They are somehow weird, so let me quote something to explain how they work.

    For checkboxes, the required attribute shall only be satisfied when one or more of the checkboxes with that name in that form are checked.

    For radio buttons, the required attribute shall only be satisfied when exactly one of the radio buttons in that radio group is checked.

    Of course you always have to validate server side because the client can always send you whatever he desires. Just use these methods for better user experience.

提交回复
热议问题