-
-
Save LSTANCZYK/fd7e7d2c9d684899993434fdfd11ea21 to your computer and use it in GitHub Desktop.
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
public class MaxWords : ValidationAttribute | |
{ | |
private int _maxWords; | |
public MaxWords(int maxWords) | |
: base("{0} has too many words") | |
{ | |
_maxWords = maxWords; | |
} | |
protected override ValidationResult IsValid(object value, ValidationContext validationContext) | |
{ | |
if (value != null) | |
{ | |
var valueAsString = value.ToString(); | |
if (valueAsString.Split(' ').Length > _maxWords) | |
{ | |
var errorMessage = FormatErrorMessage(validationContext.DisplayName); | |
return new ValidationResult(errorMessage); | |
} | |
} | |
return ValidationResult.Success; | |
} | |
} | |
public class ProductReview:IValidatableObject | |
{ | |
public int Id { get; set; } | |
[Range(1,10,ErrorMessage="Between 1 and 10 only")] | |
public int Rating { get; set; } | |
public int ProductId { get; set; } | |
[MaxWords(2)] | |
[Display(Name="Reviewer Name")] | |
[DisplayFormat(NullDisplayText="Unkown")] | |
public string ReviewerName { get; set; } | |
[MaxLength(1024)] | |
// [Required] | |
public string Comments { get; set; } | |
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) | |
{ | |
if (Rating < 2 && ReviewerName.ToLower().StartsWith("dee")) | |
{ | |
yield return new ValidationResult("Get out of here Dee"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment