Skip to content

Instantly share code, notes, and snippets.

@Dynyx
Created June 4, 2012 13:08
Show Gist options
  • Save Dynyx/2868259 to your computer and use it in GitHub Desktop.
Save Dynyx/2868259 to your computer and use it in GitHub Desktop.
Custom data validation using data annotations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
[MetadataType(typeof (FooBarMetaData))]
public class FooBar
{
// Insert FooBar related properties, methods, etc. here
private sealed class FooBarMetaData
{
[DisplayName("First Name")]
[Required(ErrorMessage = "<b>First Name</b> is required")]
[StringLength(50, ErrorMessage = "<b>First Name</b> cannot exceed 50 characters")]
public string FirstName{ get; set; }
[DisplayName("Last Name")]
[Required(ErrorMessage = "<b>Last Name</b> is required")]
[StringLength(50, ErrorMessage = "<b>Last Name</b> cannot exceed 50 characters")]
public string LastName{ get; set; }
[DisplayName("Email")]
[Required(ErrorMessage = "<b>Email</b> is required")]
[EmailValidator(ErrorMessage = "Invalid email address")]
public string EmailAddress{ get; set; }
[DisplayName("Location")]
[Required(ErrorMessage = "<b>Location</b> is required")]
[StringLength(50, ErrorMessage = "<b>Location</b> cannot exceed 50 characters")]
public string Location{ get; set; }
}
}
public class EmailValidatorAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null)
return false;
bool isValidEmail;
// Insert logic here to validate the email address
return isValidEmail;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment