如何在数据注释中为此构建正则表达式?

时间:2015-05-28 01:53:16

标签: c# regex

我正在进行数据注释验证...我需要验证一个应该只包含以下单词的属性:“Active”或“Termination”。可以使用正则表达式完成吗?因为现在我有单独的自定义类,如下所示。

Class Status

{

Override IsValid()

{

if (!(value.ToString().ToUpper() == "ACTIVE" || value.ToString().ToUpper() == "TERMINATION"))

return err;

}

}

2 个答案:

答案 0 :(得分:0)

以下正则表达式将匹配这些不区分大小写的字符串:

/^Active|Termination$/i

答案 1 :(得分:0)

如果您感兴趣,可以实际创建通用Custom Validator,而不是像OP中提到的那样创建单独的class

以下代码显示了如何创建自定义验证程序。

[AttributeUsage(AttributeTargets.Property)]
public class EqualsToTextAttribute : ValidationAttribute
{
    #region Instance Fields

    private readonly string[] textToCompare;

    #endregion

    #region Constructors

    public EqualsToTextAttribute(string[] textToCompare)
    {
        this.textToCompare = textToCompare;
    }

    #endregion

    #region Protected Methods

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value == null || string.IsNullOrWhiteSpace(value.ToString()))
        {
            return ValidationResult.Success;
        }

        if (this.textToCompare.Any(text => string.Equals(value.ToString(), text, StringComparison.OrdinalIgnoreCase)))
        {
            return ValidationResult.Success;
        }
        return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
    }

    #endregion
}

下面的代码显示了如何使用自定义数据注释属性:

    [EqualsToText(new[] { "Active", "Termination" })]
    public string TestString
    {
        get
        {
            return this.testString;
        }
        set
        {
            //This is to test the validation. Can be removed if you are using the control which applies Validation attributes automatically, e.g. DataGrid
            Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "TestString" }); 
            this.testString = value;
        }
    }