-
-
Save LSTANCZYK/70cff275ef35811f31e6225687df1e67 to your computer and use it in GitHub Desktop.
Validation attribute for ensuring a minimum number of digits entered
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 MinDigitsIncluded : ValidationAttribute, IClientValidatable | |
{ | |
private const string DefaultErrorMessage = "{0} must contain at least {1} digits."; | |
public int MinDigits { get; private set; } | |
public MinDigitsIncluded(int minDigits) : base(DefaultErrorMessage) | |
{ | |
MinDigits = minDigits; | |
} | |
public override string FormatErrorMessage(string name) | |
{ | |
return string.Format(ErrorMessageString, name, MinDigits); | |
} | |
protected override ValidationResult IsValid(object value, ValidationContext validationContext) | |
{ | |
var val = value as string; | |
if (val != null) | |
{ | |
var invalid = val.ToCharArray().Count(IsDigit) < MinDigits; | |
if (!invalid) | |
{ | |
return ValidationResult.Success; | |
} | |
} | |
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName)); | |
} | |
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) | |
{ | |
var clientValidationRule = new ModelClientValidationRule() | |
{ | |
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), | |
ValidationType = "mindigitsincluded" | |
}; | |
clientValidationRule.ValidationParameters.Add("mindigits", MinDigits); | |
return new[] { clientValidationRule }; | |
} | |
private static bool IsDigit(char input) | |
{ | |
var digits = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; | |
return digits.Contains(input); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment