使用dataannotations显示验证

时间:2013-06-24 07:22:31

标签: entity-framework data-annotations

我是Entity Framework的新手,我使用Model第一个appraoch创建了一个EDM,并使用datannotations应用了验证,一切正常但所有验证都显示在一个地方,但我想在各自旁边显示验证错误消息字段。

我写的代码如下

public partial class Hardware_services_repairs
{
public class hardwaremetadata
{
[Required]
[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage="Numbers and Special characters are not      allowed")]
public string CompanyName { get; set; }
[Required]
[RegularExpression(@"^[a-zA-Z]+$", ErrorMessage="Numbers and Special characters are not allowed")]
public string ContactName { get; set; }
//[Required]
[RegularExpression(@"^[0-9+-]+$",ErrorMessage="Only numbers are allowed")]
public string PhoneNumber { get; set; }
//[Required]
[RegularExpression(@"^[0-9+-]+$", ErrorMessage = "Only numbers are allowed")]
public string MobileNumber { get; set; }
//[Required]
[RegularExpression(@"^[A-Za-z0-9#: ]+$", ErrorMessage = "Special Characters are not allowed")]
public string Address { get; set; }
}
}

输出如下所示

List of validation errors
Numbers and Special characters are not allowed
Numbers and Special characters are not allowed
Only numbers are allowed
Only numbers are allowed
Special Characters are not allowed

但我希望每个错误信息都在各个字段旁边,请让我解决方案

提前致谢

2 个答案:

答案 0 :(得分:0)

也许,问题出在您的视图中。

“ValidationSummary”方法的参数“excludePropertyErrors”必须设置为“true”:

@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true)

然后,对于每个字段,您必须编写如下内容:

<div>
    @Html.LabelFor(model => model.CompanyName) 
</div>
<div>
    @Html.EditorFor(model => model.CompanyName)
    @Html.ValidationMessageFor(model => model.CompanyName)
</div>

答案 1 :(得分:0)

您不必添加@ Html.validationSummary

将validationMessageFor添加到要验证的每个字段并显示验证错误

<div>
    @Html.LabelFor(model => model.CompanyName) 
</div>
<div>
    @Html.EditorFor(model => model.CompanyName)
    @Html.ValidationMessageFor(model => model.CompanyName)
</div>