Skip to content Skip to sidebar Skip to footer

Field Validations In Mvc

I would like to enforce field validations on my Views in the MVC app that I am working on. For example - Limit the length of the field to 40 Ensure only alphanumeric and special

Solution 1:

This is MVC 2.0 but works just as well for 3.0 http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

Just look into Data Annotations, and do some Model Validation

EDIT:

your controller action will need something like

if(ModelState.IsValid)
{
//success logic
}
//failure logic//return to view

you will also need

@Html.ErrorMessageFor(model => model.YourProperty)

in order to see the error messages being thrown.

Read the article it does a better job explaining this then anyone else will.

Solution 2:

Just create a ViewModel object like this:

classCompany
{
    [Required]
    [StringLength(40)]
    [RegularExpression(@"someregexhere")]
    publicstring CompanyName { get; set; }
}

And bind your View to that model. In this way you'll have both serverside and clientside validation. It's really easy.

@modelCompany@using (Html.BeginForm()) {
    Html.EditorFor(x => x.CompanyName)

    <input type="submit" value="Save" />
}

Oh, this example uses Razor (MVC3), btw MVC2 works pretty much the same as far as I know.

Then just validate the incoming ViewModel in your controller by checking ModelState.IsValid.

Post a Comment for "Field Validations In Mvc"