有没有办法使 [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/