在模型中动态设置RegularExpression

时间:2014-03-05 12:54:56

标签: c# asp.net-mvc razor

我需要在模型中动态设置RegularExpression。

我的意思是,我已将RegularExpression存储在表中,然后我将该值存储在一个变量中。

现在我想在Regular Express验证中提供该变量。

[RegularExpression(VariableValue, ErrorMessage = "Valid Phone is required")]

这样的东西

string CustomExpress = "@"^(\+|\d)(?:\+?1[-. ]?)?\(?([0-9]{2})\)?[-. ]?([0-9]{1})[-. ]?([0-9]{9})$" (from Database's table)

[RegularExpression(CustomExpress, ErrorMessage = "Valid Phone is required")]
public string Phone { get; set; }

3 个答案:

答案 0 :(得分:3)

您有两个选择,要么创建自己的验证属性,要么让整个模型“可验证”。

选项1

public class RegexFromDbValidatorAttribute : ValidationAttribute
{
    private readonly IRepository _db;

    //parameterless ctor that initializes _db

    public override ValidationResult IsValid(object value, ValidationContext context)
    {
        string regexFromDb = _db.GetRegex();

        Regex r = new Regex(regexFromDb);

        if (value is string && r.IsMatch(value as string)){
            return ValidationResult.Success;
        }else{
            return new ValidationResult(FormatMessage(context.DisplayName));
        }
    }
}

然后在你的模特上:

[RegexFromDbValidator]
public string Telephone {get; set;}

选项2

public SomeModel : IValidatableObject
{
    private readonly IRepository _db;

    //don't forget to initialize _db in ctor

    public string Telephone {get; set;}

    public IEnumerable<ValidationResult> Validate(ValidationContext context)
    {

        string regexFromDb = _db.GetRegex();

        Regex r = new Regex(regexFromDb);

        if (!r.IsMatch(Telephone))
            yield return new ValidationResult("Invalid telephone number", new []{"Telephone"});
    }
}

Here's一个很好的资源,解释了如何创建验证属性

Here's使用IValidatableObject

的示例

答案 1 :(得分:0)

正如Murali所说,Data Annotation属性值必须是编译时常量。

如果您想根据其他模型值执行动态验证,可以尝试某种第三方框架(例如Fluent Validation,甚至can be integrated in ASP.NET's model validation)。

答案 2 :(得分:0)

我相信可能有一种方法可以通过继承IValidatableObject接口来实现它。每当ModelState在服务器端验证时,您都可以执行所需的所有必要检查。 它看起来像是:

public class SomeClass: IValidatableObject {
    private RegEx validation;
    public SomeClass(RegEx val) {
        this.validation = val;
    }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var results = new List<ValidationResult>();
        // perform validation logic - check regex etc...
        // if an error occurs:
        results.Add(new ValidationResult('error message'));
    }
}
相关问题