正则表达式到子字符串,然后比较

本文关键字:然后 比较 字符串 正则表达式 | 更新日期: 2023-09-27 18:18:45

我有以下代码在我的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; }

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

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

正则表达式到子字符串,然后比较

首先,如果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; }