15 error handling

22
Data Validation in ASP.NET MVC GIGO-prevention for the new age

Transcript of 15 error handling

Page 1: 15 error handling

Data Validation in ASP.NET MVC GIGO-prevention for the new age

Page 2: 15 error handling

Where should validation happen? � Controller?

�  But this is business logic, right?

� Model? �  By this time it has already gone through the

view and the controller.

� View? �  Shouldn’t have business logic in the view.

Page 3: 15 error handling

Validation should transcend them all! �  It needs to live in all three places, � View

�  Notifying user that an error has occurred �  Doing client-side validation when possible

� Model �  Business and data rules

� Controller �  Getting the error from the model and

passing it to the view.

Page 4: 15 error handling

Data Annotations to the rescue! � Setting a simple decorator in the business

model � Generates client-side JavaScript when it

can � Hooks built-in to the controller to transfer

back-and-forth � All transparent to the user � One line of code is all it takes

Page 5: 15 error handling

Data annotations

1.  Required 2.  StringLength 3.  RegularExpression 4.  Range 5.  Compare

Page 6: 15 error handling

Required [Required]![DisplayName("New password")]!public string NewPass { get; set; }!

Page 7: 15 error handling

StringLength �  [StringLength(50, MinimumLength=10)] � public string StreetAddress{ get; set; }

Page 8: 15 error handling

RegularExpression // Allow up to 40 uppercase and lowercase !// characters. Use custom error.![RegularExpression(@”^[a-zA-Z ]+$", ! ErrorMessage=”Only letters are allowed.")]!public string JobTitle;!

Page 9: 15 error handling

Range [Range(0.0, 50.0, ! ErrorMessage = "Weight between 0 & 50")]!public double ShippingWeight{ get; set; }!

Page 10: 15 error handling

Compare [Required] !public string NewPassword { get; set; }!![Required]![Compare("NewPassword", ! ErrorMessage = "Passwords don't match.")]!public string ConfirmPassword { get; set; }!

Page 11: 15 error handling

How to code the model � You just saw example of them. � Those were all code from the model or

viewmodel.

Page 12: 15 error handling

How to code the view @using (Html.BeginForm()) {! @Html.ValidationSummary(true, "Fail. Try again")! @Html.TextBoxFor(m => m.UserName)! @Html.ValidationMessageFor(m => m.UserName)! @Html.PasswordFor(m => m.Password)! @Html.ValidationMessageFor(m => m.Password)! @Html.CheckBoxFor(m => m.RememberMe)! @Html.LabelFor(m => m.RememberMe)! <input type="submit" value="Log On" />!}!

Page 13: 15 error handling

How to code the controller if (ModelState.IsValid) {! if (MembershipService.ValidateUser())! {! FormsService.SignIn();! if (!String.IsNullOrEmpty(returnUrl))! return Redirect(returnUrl);! else! return RedirectToAction("Index", "Home");! }! else! {! ModelState.AddModelError("", Bad Data!!");! }!}!// If we got this far, something failed,!// redisplay form!return View(model);!

Page 14: 15 error handling

Client-side validation code is generated automatically � Why? �  In what language?

Page 15: 15 error handling

Hands-on data annotations

Page 16: 15 error handling

We can disable client-side validation if we want to � We can turn it off if we want in web.config <appSettings>! <add key="ClientValidationEnabled" ! value="true" />! <add key="UnobtrusiveJavaScriptEnabled" ! value="true" />!</appSettings>!�  And re-enable it in each view @{ Html.EnableClientValidation(true); }!

Page 17: 15 error handling

Note that DataTypes are not validations (strictly speaking) [Required]![DataType(DataType.Email)]![DisplayName("Email Address")]!public string Email { get; set; }!� They are only used when generating templates � You probably want a Regular Expression

validation

Page 18: 15 error handling

If our needs can’t be met by other annotations, we can write custom annotations � Write class that inherits from

ValidationAttribute � Override IsValid() � Return "success" if valid and the failure

reason if not � Use your new attribute

Page 19: 15 error handling

The Custom Attribute public class SampleAttribute : ValidationAttribute!{! public override ValidationResult IsValid(object value)! {!

if ( /* some criteria */ )! return ValidationResult.Success;! else! return new ValidationResult("Failure message");!

}!

}!

Page 20: 15 error handling

Hands-on custom data annotations

Page 21: 15 error handling

Conclusion � Data Annotations enable really easy data

validations so you don't need to write a lot of JavaScript

� Based on the industry-wide accepted jQuery validation framework

� They use server-side code and generate client-side jQuery/JavaScript

Page 22: 15 error handling

Further study � Nice tutorial

�  http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html

� Microsoft's tutorial �  http://msdn.microsoft.com/en-us/

vs2010trainingcourse_aspnetmvccustomvalidation.aspx