Search code examples
htmlvue.jsvalidation

why when i use the "required" with radio i always have the message error i have to choose at least one of them whereas is the case?


Whatever I choose i have the message error as if I had chosen none.

<form class="HandleUsers__form" action="" method="post" @submit.prevent="addAdmin">
  ...
    <div>
        <legend>?????</legend>
        <div>
            <input  type="radio" name="manager" value="manager" id="manager" v-model="role" required>
            <label for="manager">Manager</label>
        </div>
        <div>
            <input type="radio" name="author" value="author" id="author" v-model="role" required>
            <label for="author">Author</label>
        </div>
    </div>
 
...
</form>

enter image description here


Solution

  • It's because they have different name values, which creates two different radio groups.

    A radio group is defined by giving each of radio buttons in the group the same name. Once a radio group is established, selecting any radio button in that group automatically deselects any currently-selected radio button in the same group.

    Because your two inputs each have the same v-model but are in different groups, selecting a value for one group automatically deselects the value from the other group, generating your error since both groups are required.

    Solution: If a user is meant to choose between Manager OR Author than they should be in the same group, i.e. they should have the same name value.

    <input type="radio" name="someGroup" value="manager" id="manager" v-model="role" required>
    <input type="radio" name="someGroup" value="author" id="author" v-model="role" required>