第一件事是,如果LastFour
提取与 的最后四位相同PAN
,为什么需要LastFour
属性。您可以只对该部分进行子串化并获取最后四位数字。
但是如果你真的需要这样做,你可以为此创建一个自定义属性,
public class LastFourDigitsAttribute : ValidationAttribute, IClientValidatable
{
private string panPropertyname;
public LastFourDigitsAttribute(string pan)
: base()
{
if (string.IsNullOrEmpty(pan))
{
throw new ArgumentNullException("pan");
}
this.panPropertyname = pan;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
// This is the name of the method added to the jQuery validator method (must be lower case)
ValidationType = "lastfour"
};
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
PropertyInfo panPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(panPropertyname);
if (panPropertyInfo != null)
{
var panPropertyValue = panPropertyInfo.GetValue(validationContext.ObjectInstance, null);
if (panPropertyValue != null)
{
if (value.ToString() != panPropertyValue.ToString().Substring(panPropertyValue.ToString().Length - 4);)
{
return new ValidationResult(ErrorMessage);
}
}
}
}
return ValidationResult.Success;
}
}
用法,
[LastFourDigits("PAN", ErrorMessageResourceName = "CustomerEnrollment_CardLastFourInvalidMessage", ErrorMessageResourceType = typeof(Messages))]
[Required(ErrorMessageResourceName = "CustomerEnrollment_CardLastFourRequiredMessage", ErrorMessageResourceType = typeof(Messages))]
[RegularExpression("^[0-9]{4}$", ErrorMessageResourceName = "CustomerEnrollment_InvalidLastFour", ErrorMessageResourceType = typeof(Messages))]
public string LastFour { get; set; }