c# - Web Api 使用 DataAnnotations 验证可选 Url

标签 c# validation asp.net-web-api2

有没有办法使 [Url] 验证可选?

举个例子

public class Company 
{
        [Required, StringLength(63, MinimumLength = 2)]
        public string Name { get; set; }

        [Url, StringLength(127)]
        public string Url { get; set; }
}

上面的验证完全按照我的预期工作,但 Url 属性不能是可选的。我不希望验证在空白时抛出错误,而是希望它仅在用户输入值时进行验证。

更新: 考虑哈米德·沙希德的以下回答。我只是添加了一个条件来解决我的问题,直到出现更好的情况:

        //Making url validation optional, fix
        if (company.Url == string.Empty) company.Url = null;

最佳答案

URLAttribute 验证对于 null 值返回 true。如果 URL 属性的值为 NULL,则它将被视为有效值。如果将其设置为空字符串,则会被视为无效。

下面的代码显示了 UrlAttribute 类的反编译版本

// System.ComponentModel.DataAnnotations.UrlAttribute
[__DynamicallyInvokable]
public override bool IsValid(object value)
{
    if (value == null)
    {
        return true;
    }
    string text = value as string;
    if (UrlAttribute._regex != null)
    {
        return text != null && UrlAttribute._regex.Match(text).Length > 0;
    }
    return text != null && (text.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase) || text.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase) || text.StartsWith("ftp://", StringComparison.InvariantCultureIgnoreCase));
}

关于c# - Web Api 使用 DataAnnotations 验证可选 Url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47208339/

相关文章:

c# - 我如何过滤所有字段名称的 C# dataGridView?

c# - 索引超出 GridViewRow 范围

regex - Angular 2表单验证模式正则表达式错误

javascript - 验证 JavaScript 函数名称

c# - 使用FilterAttributes的Web API异常处理

c# - 带有响应 header 的单元测试 webapi Controller

asp.net-web-api - 使用路由与查询字符串参数是错误的吗?

javascript - 如何在 asp.net.core 中使用 Ajax 发布表单数据和文件?

c# - 鼠标进入/离开Form和Button子事件问题

validation - 验证准确性/损失是否会影响 caffe 中的训练