正则表达式子串然后比较

时间:2013-06-18 05:30:07

标签: c# asp.net-mvc regex

我的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; }

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

有人能帮助我吗?提前谢谢!

1 个答案:

答案 0 :(得分:1)

首先,如果LastFourPAN的后四位数相同,那么为什么需要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; }