1

我的 mvc 应用程序中有以下代码:

[Required(ErrorMessageResourceName = "NumberRequired",  ErrorMessageResourceType = typeof (Messages))]
[RegularExpression("^[0-9]{16}$", ErrorMessageResourceName = "NumberRequired", ErrorMessageResourceType = typeof (Messages))]
public string number{ get; set; }

[Required(ErrorMessageResourceName = "LastFourRequired", ErrorMessageResourceType = typeof(Messages))]
[RegularExpression("^[0-9]{4}$", ErrorMessageResourceName = "LastFourRequired", ErrorMessageResourceType = typeof(Messages))]
public string lastfour{ get; set; }

我的问题是我需要验证最后四个。它必须等于数字的最后四位。我需要在这段代码中进行验证。

有人可以帮助我吗?提前致谢!

4

1 回答 1

1

第一件事是,如果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; }
于 2013-06-18T05:45:50.397 回答