MrMistreater

Using data annotations to validate data in MVC application

May 18th, 2012
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.40 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.ComponentModel.DataAnnotations;
  5. using System.Linq;
  6.  
  7. [MetadataType(typeof (FooBarMetaData))]
  8. public class FooBar
  9. {
  10.     // Insert FooBar related properties, methods, etc. here
  11.  
  12.     private sealed class FooBarMetaData
  13.     {
  14.         [DisplayName("First Name")]
  15.         [Required(ErrorMessage = "<b>First Name</b> is required")]
  16.         [StringLength(50, ErrorMessage = "<b>First Name</b> cannot exceed 50 characters")]
  17.         public string FirstName{ get; set; }
  18.  
  19.         [DisplayName("Last Name")]
  20.         [Required(ErrorMessage = "<b>Last Name</b> is required")]
  21.         [StringLength(50, ErrorMessage = "<b>Last Name</b> cannot exceed 50 characters")]
  22.         public string LastName{ get; set; }
  23.  
  24.         [DisplayName("Email")]
  25.         [Required(ErrorMessage = "<b>Email</b> is required")]
  26.         [EmailValidator(ErrorMessage = "Invalid email address")]
  27.         public string EmailAddress{ get; set; }
  28.  
  29.         [DisplayName("Location")]
  30.         [Required(ErrorMessage = "<b>Location</b> is required")]
  31.         [StringLength(50, ErrorMessage = "<b>Location</b> cannot exceed 50 characters")]
  32.         public string Location{ get; set; }
  33.     }
  34. }
  35.  
  36. public class EmailValidatorAttribute : ValidationAttribute
  37. {
  38.     public override bool IsValid(object value)
  39.     {
  40.         if (value == null)
  41.             return false;
  42.  
  43.         bool isValidEmail;
  44.  
  45.         // Insert logic here to validate the email address
  46.        
  47.         return isValidEmail;
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment