实现 DataAnnotations 验证属性时,我应该调用 base.IsValid() 吗?
我正在创建一个 DataAnnotations 验证属性,用于使用与 jQuery 相同的模式来匹配电子邮件(是的,它必须以前完成过,但我找不到它......)并且我不确定我到底在做什么应该覆盖以及是否应该调用基类上的方法。目前我有这样的实现:
public class EmailAttribute : ValidationAttribute
{
const string emailPattern = // long regex string
private Regex emailRegex = new Regex(emailPattern, RegexOptions.Compiled);
public override bool IsValid(object value)
{
return (value is string) &&
emailRegex.IsMatch((string)value) &&
base.IsValid(value);
}
}
是否需要重写其他方法才能使其正常工作?我应该像上面那样调用 base.IsValid(value)
,还是这样做是多余的/完全错误的?
欢迎任何评论。
I'm creating a DataAnnotations validation attribute for matching emails using the same pattern as jQuery (yes, it must have been done before, but I can't find it...) and I'm not sure on exactly what I'm supposed to override and whether methods on the base classes should be called or not. Currently I have this implemnetation:
public class EmailAttribute : ValidationAttribute
{
const string emailPattern = // long regex string
private Regex emailRegex = new Regex(emailPattern, RegexOptions.Compiled);
public override bool IsValid(object value)
{
return (value is string) &&
emailRegex.IsMatch((string)value) &&
base.IsValid(value);
}
}
Is there any other methods I need to override for this to work correctly? Should I call base.IsValid(value)
as above, or is it redundant/flat out wrong to do so?
Any comments are welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要覆盖其他任何内容,也不应该调用 base.IsValid。
仅供参考:您可能会考虑为此继承 RegularExpressionAttribute,以便选择客户端选项。例如...
此外,这可能对您有用:
http://foolproof.codeplex.com/
这是一组本来应该在 MVC 中的验证器。做得很好,来源很有启发性。五月份以来就没有动过,希望现在还活跃。
You don't need to override anything else and you should not call base.IsValid.
FYI: You might consider inheriting from RegularExpressionAttribute for this so that you pick up client side options. For example...
Also, this may be useful to you:
http://foolproof.codeplex.com/
It's a set of validators that should have been in MVC. Nicely done and the source is instructive. Hasn't moved since May, hoping it's still active.