You are on page 1of 30

The client validation logic gives users instant feedback on the information they enter into a form,

and is an expected feature in today's web applications. Meanwhile, the server validation logic is in
place because you should never trust information arriving from the network.

DATA ANNOTATIONS AND


VALIDATION
By
Amareswara Rao

The default approach of validation using attributes known as data annotations .


Not only do you want validation logic executing in the browser, but you also must have validation
logic running on the server.
1
2
USING VALIDATION
ANNOTATIONS
System.ComponentModel.DataAnnotations

Required

3
STRINGLENGTH
Wikipedia says the longest name ever used belonged to a German
typesetter who lived in Philadelphia. His full name is more than 500
characters long.

4
REGULAREXPRESSION
you'd like to ensure the Email property of an Order contains a valid,
working e-mail address.

[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]

public string Email { get; set; }

the error message looks like someone sprinkled catnip on a keyboard


before letting a litter of Norwegian
5
Forest Cats run wild.
RANGE
The Range attribute specifies minimum and maximum constraints for a
numerical value.

[Range(35,44)]

public int Age { get; set; }

The first parameter to the attribute is the minimum value, and the second
parameter is the maximum value. The values are inclusive.

[Range(typeof(decimal), "0.00", "49.99")]

public decimal Price { get; set; }


VALIDATION ATTRIBUTES
FROM SYSTEM.WEB.MVC
Remote attribute.

The Remote attribute enables you to perform client-side validation with a server callback.

[Remote("CheckUserName", "Account")]

public string UserName { get; set; }

Inside the attribute you can set the name of the action, and the name of the controller the
client code should call.
Compare attribute.

Compare ensures two properties on a model


object have the same value.

Remote and Compare only exist because data annotations are


extensible.
CUSTOM ERROR MESSAGES
AND LOCALIZATION
The preceding code assumes you have a resource
file in the project named ErrorMessages.resx with
the appropriate entries inside ( LastNameRequired
and LastNameTooLong ).
LOOKING BEHIND THE
ANNOTATION CURTAIN
The validation features of ASP.NET MVC are part of a coordinated system involving
model binders, model metadata, model validators, and model state.

Validation and Model Binding

By default, the ASP.NET MVC framework executes validation logic during model binding.

You can also explicitly request model binding using the


UpdateModel or TryUpdateModel methods of a controller:
Once the model binder is finished updating the model properties with new values, the
model binder uses the current model metadata and ultimately obtains all the validators
for the model.

The MVC run time provides a validator to work with data annotations (the
DataAnnotationsModelValidator ).

This model validator can find all the validation attributes and execute the validation logic
inside. The model binder catches all the failed validation rules and places them into model
state.
Validation and Model State

Not only does model state contain all the values a user attempted to put
into model properties, but model state also contains all the errors
associated with each property (and any errors associated with the model
object itself).

If there are any errors in model state, ModelState.IsValid returns false.

without providing a value for LastName following expressions will return


true

to see the error message associated with the failed validation:


var lastNameErrorMessage =
ModelState["LastName"].Errors[0].ErrorMessage;
CONTROLLER ACTIONS AND
VALIDATION ERRORS
You could also implement the action using an explicit call to
UpdateModel or TryUpdateModel
CUSTOM VALIDATION LOGIC
Packaging validation logic into a custom data annotation

Packaging validation logic into a model object itself

Putting validation logic into a custom data annotation means you can easily
reuse the logic across multiple models. Of course, you have to write the
code inside the attribute to work with different types of models, but when
you do, you can place the new annotation anywhere.

On the other hand, adding validation logic directly to a model object often
means the validation logic itself is easier to write (you only need to worry
about the logic working with a single type of object). It is, however, more
difficult to reuse the logic.
CUSTOM ANNOTATIONS
IVALIDATABLEOBJECT
The method the MVC run time calls to perform
validation is named Validate instead of IsValid , but more
important, the return type and parameters are different.

The return type for Validate is an


IEnumerable<ValidationResult> instead of a single
ValidationResult , because the logic inside is ostensibly
validating the entire model and might need to return
more than a single validation error.

There is no value parameter passed to Validate because


you are inside an instance method of the model and can
refer to the property values directly.
DISPLAY
SCAFFOLDCOLUMN
The ScaffoldColumn attribute hides a property from
HTML helpers such as EditorForModel and
DisplayForModel :

[ScaffoldColumn(false)]

public string Username { get; set; }

With the attribute in place, EditorForModel will no longer


display an input or label for the Username field.
DISPLAYFORMAT
[DisplayFormat(ApplyFormatInEditMode=true,
DataFormatString="{0:c}")]

public decimal Total { get; set; }


READONLY

[ReadOnly(true)]

public decimal Total { get; set; }


DATATYPE
[Required]

[DataType(DataType.Password)] [Display(Name="Password")]

public string Password { get; set; }


UIHint

The UIHint attribute gives the ASP.NET MVC run time the
name of a template to use when rendering output with the
templated helpers (like DisplayFor and EditorFor ).

HiddenInput

The HiddenInput attribute lives in the System.Web.Mvc


namespace

Hidden inputs are a great way to keep information in a form


so the browser will send the data back to the server, but the
user won't be able to see or edit the data

You might also like