【发布时间】:2011-12-21 19:27:15
【问题描述】:
在我的 ASP.net MVC3 应用程序的域模型上,我构建了一个自定义验证器,以确保以特定格式插入出生日期。
我将出生日期保存为字符串,因为我的应用程序需要保存死去已久的人的出生日期,例如柏拉图、苏格拉底等,以防您想知道为什么不使用DateTime 来保存出生日期。
这是我的自定义验证器代码:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ValidateDODDOB : ValidationAttribute
{
// Error Message
private const string DefaultErrorMessage = "Please type the date in the format specified.";
// Gets or sets the Regular expression.
private Regex Regex { get; set; }
// The pattern used for Date of Birth and Date of Death validation.
public string Pattern { get { return @"^(?:\d+\s)?(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)?(?:\s?\d+)(?:\sBCE)?$"; } }
// Initializes a new instance of the VerifyDODDOB class.
public ValidateDODDOB() : base(DefaultErrorMessage)
{
this.Regex = new Regex(this.Pattern);
}
// Determines whether the specified value of the object is valid.
// true if the specified value is valid; otherwise, false.
public override bool IsValid(object value)
{
// convert the value to a string
var stringValue = Convert.ToString(value);
var m = Regex.Match(stringValue);
return m.Success;
}
}
上述方法在验证和阻止创建/编辑操作进入数据库方面起作用。但是当表单返回视图时没有显示错误消息!
针对评论 01 的更新:
抱歉 Olive,我也应该发布视图代码。这里是:
<div class="inputField">
@Html.LabelFor(x => x.DOB, "Date of Birth")
@Html.TextBoxFor(model => model.DOB)
@Html.ValidationMessageFor(model => model.DOB)
</div>
所以是的,我已经告诉它也显示验证消息。就 AJAX 而言,它不是通过 AJAX。就像你说的,它是在一个完整的 POST 请求之后。
【问题讨论】:
-
您的视图代码是否使用@Html.ValidationMessageFor(m => m.PropertyWithValidateDODDOBAttribute)?您可以发布您的视图代码吗?此外,您的创建/编辑操作是否通过 AJAX 访问?还是在完整的 POST 请求后没有显示验证消息?
-
你能发布你的控制器和模型吗?可能是一些小问题,例如没有使用 ValidateDODDOB 属性注释模型中的 DOB,或者在控制器中缺少 ModelState.IsValid 等。它肯定也有助于发布它们。
标签: asp.net-mvc asp.net-mvc-3 customvalidator