FernandoPaiva
FernandoPaiva

Reputation: 4462

How do I make an attribute Boolean as [Required] to use with a RadioButtonFor?

I'm trying to create an attribute and add the DataAnnotation [Required] to use with RadioButtonFor. This RadioButtonFor when the page is loaded it is unchecked and I need this because the user need to choose one of two options (yes/no) to next step. The problem is I can't make this attribute required.

How could I do this ?

Model

[Required(ErrorMessage="Please, choose one option")]
public Boolean isGroupMember { get; set; }

HTML

<div class="form-group">
                        <label for="@Html.IdFor(model => model.isGroupMember )" class="cols-sm-2 control-label">Choose one option ? <img src="~/Imagens/required.png" height="6" width="6" title="requerido"></label>
                        <table class="table">
                            <tr>
                                <td><strong>Yes</strong>@Html.RadioButtonFor(model => model.isGroupMember , 1, new { Class = "form-control" })</td>
                                <td><strong>No</strong>@Html.RadioButtonFor(model => model.isGroupMember , 0, new { Class = "form-control" })</td>
                            </tr>
                        </table> 
                        @Html.ValidationMessageFor(model => model.isGroupMember )                     
                    </div><!--/member group-->

Upvotes: 0

Views: 46

Answers (2)

Shyju
Shyju

Reputation: 218892

The 2 possible values of a boolean field is true and false. The default value of the boolean field is false. So even if the user did not select anything in the form, When the model validation framework inspects the value of this property, the value(false,default value) is a valid boolean value, hence will pass the model validation.

To make the required validation works, you need to make it a nullable boolean type

[Required(ErrorMessage = "Please, choose one option")]
public Boolean? isGroupMember2 { get; set; }

I would also suggest switching to PascalCasing for property names (IsGroupMember2 instead of isGroupMember2)

[Required(ErrorMessage = "Please, choose one option")]
public bool? IsGroupMember2 { get; set; }

You also probable want to change the value of the radio buttons to True and False instead of 1 and 0.

@Html.RadioButtonFor(model => model.IsGroupMember , true, new { Class = "form-control" })
@Html.RadioButtonFor(model => model.IsGroupMember , false, new { Class = "form-control" })

Upvotes: 3

dev8989
dev8989

Reputation: 349

Try replacing your radio buttons with the following code.

<td><strong>Yes</strong>@Html.RadioButtonFor(model => model.isGroupMember , 1, new { Class = "form-control" }, required = "required")</td>
<td><strong>No</strong>@Html.RadioButtonFor(model => model.isGroupMember , 0, new { Class = "form-control" },required = "required")</td>

Upvotes: 1

Related Questions