【发布时间】:2016-04-05 14:12:09
【问题描述】:
所以我一直在这里撞墙。我完全按照教程进行操作,但我不知道为什么这个自定义验证不起作用。它应该验证电话号码。
更短的请到最后
自定义属性:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class CustomPhoneAttribute : DataTypeAttribute, IClientValidatable
{
private static readonly string[] ddds = new[] { ... };
private static Regex regex = new Regex(@"^(\([0-9]{2}\)) ([0-9]{5}-[0-9]{4}|[0-9]{4}-[0-9]{4}$", RegexOptions.Compiled);
private const string DefaultErrorMessage = "{0} must be a phone number.";
public CustomPhoneAttribute()
: base(DataType.PhoneNumber)
{
ErrorMessage = DefaultErrorMessage;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name);
}
private bool ValidatePhone(string phone)
{
if (regex.Match(phone).Success)
{
var ddd = phone.Substring(1, 2);
if (ddds.Contains(ddd))
{
var phoneParts = phone.Substring(5).Split('-');
}
// TODO: perform further evaluation base on
// ddd, first digit and extra 9.
// For now we only check the ddd exists.
return true;
}
return false;
}
public override bool IsValid(object value)
{
if (value == null)
{
return true;
}
return ValidatePhone((string)value);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "brphone"
};
}
型号:
{...}
[CustomRequired] // this works.
[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone")]
[CustomPhone]
public string Phone { get; set; }
{...}
Javascript:
$.validator.addMethod("brphone",
function (value, element) {
if (!this.optional(element)) {
// perform validation.
return true;
}
return true;
});
$.validator.unobtrusive.adapters.addBool("brphone");
查看:
@Html.TextBoxFor(m => m.Phone, new { @class = "form-control phonemask-client", placeholder = "(xx) xxxxx-xxxx" })
一切似乎都检查过了,服务器端和客户端验证仍然没有工作。
已确定部分内容(可能来自微软的错误)
如果我从数据注释类中删除正则表达式对象,它就像一个魅力。现在,为什么会这样,我不知道!如果我附加一个调试器,当它遇到正则表达式声明并单击单步继续调试时,程序只是返回到网页并且没有任何反应。
是否禁止在数据注解中使用正则表达式?
【问题讨论】:
标签: c# asp.net-mvc validation asp.net-mvc-5