Skip to content

Instantly share code, notes, and snippets.

@ioab
Last active September 28, 2015 20:52
Show Gist options
  • Select an option

  • Save ioab/3ae566528ee5d2c17d03 to your computer and use it in GitHub Desktop.

Select an option

Save ioab/3ae566528ee5d2c17d03 to your computer and use it in GitHub Desktop.
A simple validatable model class.
/// <summary>
/// A simple Model with validation logic built within it.
/// Another approach of validation besides &quot; Data Annotations &quot; is to implement IValidatableObject interface.
/// </summary>
public class User : IValidatableObject
{
public int Age { get; set; }
public string Name { get; set; }
public override IEnumerable<ValidationResult> Validate(ValidationContext context)
{
if (string.IsNullOrWhiteSpace(Name))
{
yield return new ValidationResult("Name cannot be empty.", new[] { "Name" });
}
if (Age > 100 || Age < 1)
{
yield return new ValidationResult("Age is invalid", new[] { "Age" });
}
if (Name.Split(' ').Length > 5)
{
yield return new ValidationResult("Name appears to be improper.", new[] { "Name" });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment