起因
现在用手机上网的人越来越多了,过去那种即没有手机,也没有Email的人,我估计已经很少了,所以我决定我的网站用手机或者Email登录。可是ASP.NET MVC默认的模板里面,是用电子邮件登录的。我看了网上中英文很多人的文章,基本上都绕开了DataAnnotation,这样复用性就不高。我决定自己写一个Annotation。
寻觅
我在Google上找了一圈,然后在Visual Studio的Nuget里面又找了一圈,又在百度和csdn找了一圈,没有同类的东西,所以只好自己做。
资源
微软现在已经公布了.NET的源代码,这给我们带来了很大的好处。我们不用重新发明轮子了,只需要在原来的基础上改。
通过Google,直接找到了代码
https://referencesource.microsoft.com/#System.ComponentModel.DataAnnotations/DataAnnotations/PhoneAttribute.cs
有图有真相
PS,谁说微软不开源。
复制代码
这是 ASP.NET MVC默认的EmailAddress的错误信息。
如果输入手机号,也报错
我们的目标是,输入手机号以后,不在报错。
把微软代码放在新项目中
现在,我们把微软源代码里面的AppSettings.cs,EmailAddressAttribute.cs和PhoneAttribute.cs复制出来,放在一个c# class library中。
修改EmailAddressAttribute
简单修改,使得代码能够运行。
在EmailAddressAttribute的Constructor中,注释掉
DefaultErrorMessage = DataAnnotationsResources.PhoneAttribute_Invalid;
改成
base.ErrorMessage = "The Email/Phone field is not a valid e-mail address.";
完整的Constructor如下:
public EmailAdressAttribute()
: base(DataType.PhoneNumber)
{
// DevDiv 468241: set DefaultErrorMessage not ErrorMessage, allowing user to set
// ErrorMessageResourceType and ErrorMessageResourceName to use localized messages.
//DefaultErrorMessage = DataAnnotationsResources.PhoneAttribute_Invalid;
base.ErrorMessage = "The Email/Phone field is not a valid e-mail address.";
}
修改PhoneAttribute.cs
这里,我不说了。不明白的,请关闭浏览器,推出软件行业。
修改AppSettings.cs
注释掉
//_disableRegEx = BinaryCompatibility.Current.TargetsAtLeastFramework472;
和
//using System.ComponentModel.DataAnnotations.Util;
现在,项目应该编译通过了。如果没有,那肯定是我的错。不过,没关系,我在文章结尾会给出源代码Github地址。
修改web
更改web.config
把
<add key="ClientValidationEnabled" value="true" />
改成
<add key="ClientValidationEnabled"