dotNetNewbie
dotNetNewbie

Reputation: 789

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 -

I used the following to restrict the field length:

<div>
<%= Html.TextBoxFor(c => c.CompanyName, new { style = "width:300px", maxlength = "40" })%></div>

How do I ensure that only alphanumeric and special characters can be entered in the textboxes?

EDIT: I changed the property in my model to

        [DataMember(EmitDefaultValue = false)]
        [Required(ErrorMessage="CompanyName is Required")]
        [StringLength(40, ErrorMessage = "Must be under 40 characters")]
        public string CompanyName { get; set; }

To test I tried saving a blank CompanyName hoping to get a Server Error since it is Required. However, it saves the blank Company Name. Any ideas what might be missing?

Upvotes: 2

Views: 1135

Answers (2)

Leon Cullens
Leon Cullens

Reputation: 12476

Just create a ViewModel object like this:

class Company
{
    [Required]
    [StringLength(40)]
    [RegularExpression(@"someregexhere")]
    public string 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.

@model Company

@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.

Upvotes: 3

Blast_dan
Blast_dan

Reputation: 1125

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.

Upvotes: 3

Related Questions