How to validate radio button list by using Microsoft MVC - ModelState Validation

4/1/2014·2 min read
If you want to validate your radio botton list when click button.(Just sample)

    Must be select one.

This article is about how to set up a validation for radio button list. So I'll use MVC's Model State to complete server side valistion and client side validation. The way I'm doing is using ENUM for display radio buttons. Following example will be if you have question like A, B, C, D, and need to validate choose one of them. By the way, you could group your radio button list, so always choose one, but this's article just about if you want to validate your raido button for reference.

So basically, you need to following works.

Model Property + Model State(Post) + Control(client)

1. create enum for your radio button's select value

So, if client send 0 which is undefine, we know radio button is not selected.

2. add model and error message.

Error Message will be display when client validation happened at this case.

3. at server side post

4. check property from client

so when client post to server, check the property. In this case, check it's Enum.Undefine or not, if it's undefine, then, add error message to display. First parameter "key" will be your control's name. next parametr will be the error message to display. Error message will display when server validation happened, it'll display the one set up at property's attribute.

5. set up Razor view

6. if ModelState's key is empty, error message will come to here.

This's one way to imprement radio button server side and client side validation.

You could go to following page to check demo.

DEMO

If you're first add mvc validation,you might need to add some setting to your file. You could reference following blog to check it out.

MVC Validation Setting