Last active
September 28, 2015 20:52
-
-
Save ioab/3ae566528ee5d2c17d03 to your computer and use it in GitHub Desktop.
A simple validatable model class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /// <summary> | |
| /// A simple Model with validation logic built within it. | |
| /// Another approach of validation besides " Data Annotations " 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