本文介绍了在模型中动态设置RegularExpression的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在模型中动态设置RegularExpression.
I need to set RegularExpression Dynamically in Model.
我的意思是,我已经将RegularExpression存储在表中,然后将该值存储在一个变量中.
I mean, I have stored RegularExpression in table and then I will store that value in one variable.
现在,我想在Regular Express验证中提供该变量.
Now I want to supply that variable in Regular Express validation.
即
[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; }
推荐答案
您有两个选择,要么创建自己的验证属性,要么将整个模型设置为"validatable".
You have two options, either you create your own validation attribute or you make your whole model "validatable".
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 a good resource that explains how to create validation attributes
此处 IValidatableObject的使用
Here's an example of using IValidatableObject
这篇关于在模型中动态设置RegularExpression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!