LSTANCZYK
9/25/2017 - 1:34 AM

Validation attribute for ensuring a minimum number of digits entered

Validation attribute for ensuring a minimum number of digits entered

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);
    }
}