gpt4 book ai didi

c# - 未触发 MVC 5 自定义验证属性

转载 作者:太空宇宙 更新时间:2023-11-03 12:48:36 25 4
gpt4 key购买 nike

所以我一直在用头撞墙。我严格按照教程进行操作,但我不知道为什么此自定义验证不起作用。它应该验证电话号码。

短到最后

自定义属性:

[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" })

一切似乎都已检查完毕,但服务器端和客户端验证仍然无效。

计算出其中的一部分(可能是微软的错误)

如果我从数据注释类中删除 regex 对象,它会非常有效。现在,为什么会这样,我不知道!如果我附加一个调试器,当它遇到正则表达式声明并且我单击 step over 继续调试时,程序只是返回到网页,没有任何反应。

是否禁止在数据注释中使用正则表达式?

最佳答案

您的正则表达式中缺少括号,这会在实例化属性时导致错误。

// missing ')' between the {4} and $
private static Regex regex = new Regex(@"^(\([0-9]{2}\)) ([0-9]{5}-[0-9]{4}|[0-9]{4}-[0-9]{4})$", RegexOptions.Compiled);

由于字段上的 static 关键字,我们在运行时没有看到错误。

假设您的属性如下所示:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class CustomPhoneAttribute : DataTypeAttribute
{
public static string MyString = GetValue();

public CustomPhoneAttribute()
: base(DataType.PhoneNumber)
{
}

private static string GetValue()
{
throw new Exception();
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
return base.IsValid(value, validationContext);
}
}

当使用 static 关键字时,运行时需要在实例化类本身之前的某个时间点初始化类型级别的值。但是,当这种情况发生时会导致崩溃,因为 GetValue 代码会抛出异常。当 MVC 查看模型的数据注释时会发生该错误,并且它将依次忽略该属性(因为它无法实例化)。

通过删除 static 关键字,您可以在实例化注释时在构造函数中抛出错误,因此它首先被抛入您的代码中,调试器可以中断它。

关于c# - 未触发 MVC 5 自定义验证属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36428862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com