我已经创建了一个表单,当我用它加载页面时,我会在提交表单之前看到验证消息。为什么?你可以download my code from github
The similar question. It's because of mvc4
@model MyMustAgreeValidation.Models.NewUserProfileModel
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
@Html.MyEditFor(m=>m.Login)
@Html.MyEditFor(m=>m.Password)
@Html.MyEditFor(m=>m.ConfirmPassword)
@Html.MyEditFor(m=>m.DisplayName)
@Html.MyEditFor(m=>m.Email)
@Html.MyEditFor(m=>m.Homepage)
@Html.MyEditFor(m=>m.AgreementAccepted)
<p><input type="submit" value="@CreateRes.CreateProfileButton"/></p>
</fieldset>
}
Html.MyEditFor
public static MvcHtmlString MyEditFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression)
{
return html.Partial("Item", new LabelEditorValidation() { Label = html.LabelFor(expression), Editor = html.EditorFor(expression), Validation = html.ValidationMessageFor(expression) });
}
Item
是部分视图:
@model MyMustAgreeValidation.Models.LabelEditorValidation
<div class="editor-label">
@Model.Label
</div>
<div class="editor-field">
@Model.Editor
@Model.Validation
</div>
LabelEditorValidation:
public class LabelEditorValidation
{
public MvcHtmlString Label { get; set; }
public MvcHtmlString Editor { get; set; }
public MvcHtmlString Validation { get; set; }
}
脚本包括:
<script src="/Scripts/jquery-1.7.1.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="/Scripts/Validation/EqualAttribute.js"></script>
表单模型NewUserProfileModel:
public class NewUserProfileModel : UserProfileModel, IValidatableObject
{
[Display(Name="Password", ResourceType = typeof(NewUserProfileRes))]
[DataType(DataType.Password)]
[Required(ErrorMessageResourceName = "FieldIsRequired", ErrorMessageResourceType = typeof(ErrorsRes))]
[StringLengthRange(6, 64, ErrorMessageResourceType = typeof(ErrorsRes), ErrorMessageResourceName = "InvalidStringLength")]
public string Password { get; set; }
[Display(Name="ConfirmPassword", ResourceType = typeof(NewUserProfileRes))]
[DataType(DataType.Password)]
[Compare("Password", ErrorMessageResourceType = typeof(NewUserProfileRes), ErrorMessageResourceName = "PasswordsDontMatch")]
public string ConfirmPassword { get; set; }
[Display(Name="AgreementAccepted", ResourceType = typeof(NewUserProfileRes))]
[Equal(true, ErrorMessageResourceType = typeof(NewUserProfileRes), ErrorMessageResourceName = "MustAgreeWithEULA")]
public bool AgreementAccepted { get; set; }
public NewUserProfileModel()
{
var property = GetType().GetProperty("Login");
var list = property.GetCustomAttributes(true);
foreach (var item in list)
{
Console.WriteLine(item);
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var userRepository = new UserRepository();
if (userRepository.IsLoginExists(Login))
{
yield return new ValidationResult(NewUserProfileRes.LoginAlreadyExists, new []{"Login"});
}
}
UserProfileModel:
public class UserProfileModel
{
[Display(Name = "Login", ResourceType = typeof(UserProfileRes))]
[DataType(DataType.Text)]
[Required(ErrorMessageResourceName = "FieldIsRequired", ErrorMessageResourceType = typeof(ErrorsRes))]
[StringLengthRange(3, 64, ErrorMessageResourceName = "InvalidStringLength", ErrorMessageResourceType = typeof(ErrorsRes))]
public string Login { get; set; }
[Display(Name="DisplayName", ResourceType = typeof(UserProfileRes))]
[DataType(DataType.Text)]
[Required(ErrorMessageResourceName = "FieldIsRequired",
ErrorMessageResourceType = typeof(ErrorsRes))]
[StringLengthRange(3, 32,
ErrorMessageResourceName = "InvalidStringLength",
ErrorMessageResourceType = typeof(ErrorsRes))]
public string DisplayName { get; set; }
[Display(Name = "Email", ResourceType = typeof(UserProfileRes))]
[DataType(DataType.EmailAddress)]
[Required(ErrorMessageResourceType = typeof(ErrorsRes), ErrorMessageResourceName = "FieldIsRequired")]
[RegularExpression(@"[\w\.-]*[a-zA-Z0-9_]@[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]", ErrorMessageResourceType = typeof(ErrorsRes), ErrorMessageResourceName = "InvalidEmailAddress")]
[StringLength(64, ErrorMessageResourceType = typeof(ErrorsRes), ErrorMessageResourceName = "StringTooLong")]
public string Email { get; set; }
[Display(Name="Homepage", ResourceType = typeof(UserProfileRes))]
[DataType(DataType.Url)]
[RegularExpression(@"(http(s)?://)?([\w-]+\.)+[\w-]+(/[\w- ;,./?%&=]*)?", ErrorMessageResourceType = typeof(ErrorsRes), ErrorMessageResourceName = "IvalidUrl")]
[StringLength(96,
ErrorMessageResourceType = typeof(ErrorsRes), ErrorMessageResourceName = "StringTooLong")]
public string Homepage { get; set; }
}
EqualAttribute.js:
jQuery.validator.addMethod("equal", function (value, element, param) {
if($(element).attr("type")=="checkbox")
{
value = String($(element).attr("checked"));
param = param.toLowerCase();
}
return (value == param);
});
jQuery.validator.unobtrusive.adapters.addSingleVal("equal", "valuetocompare");