You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET中如何用Data Annotations验证属性值为指定文本?

如何用Data Annotations验证属性值为特定文本

可以通过Data Annotations实现这类验证,有两种常用方案:

方案一:使用内置的RegularExpressionAttribute

利用正则表达式的精确匹配规则,就能限制属性值必须等于指定文本。比如要求ClassName必须是“science”,可以用^science$作为正则表达式(^表示字符串开头,$表示结尾,确保完全匹配)。

代码示例:

using System.ComponentModel.DataAnnotations;

public class Student
{
    [RegularExpression(@"^science$", ErrorMessage = "班级名称必须为'science'")]
    public string ClassName { get; set; }
}

方案二:自定义固定值验证属性

如果觉得正则不够直观,可以自定义一个专门的验证属性,继承ValidationAttribute并实现逻辑判断,这样代码可读性更强,也方便复用。

自定义属性代码:

using System.ComponentModel.DataAnnotations;

public class FixedValueAttribute : ValidationAttribute
{
    private readonly string _requiredValue;

    public FixedValueAttribute(string requiredValue)
    {
        _requiredValue = requiredValue;
        ErrorMessage = $"属性值必须为'{_requiredValue}'";
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var stringValue = value as string;
        if (stringValue != _requiredValue)
        {
            return new ValidationResult(ErrorMessage);
        }
        return ValidationResult.Success;
    }
}

使用示例:

public class Student
{
    [FixedValue("science")]
    public string ClassName { get; set; }
}

两种方案都能满足需求:正则方式快速简单,适合单次使用;自定义属性更清晰,适合需要多次复用固定值验证的场景。

内容的提问来源于stack exchange,提问作者beginner007

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:37:33