在MVC3中获取自定义验证属性仅在提交时触发,而不是在输入失去焦点时触发

时间:2012-01-23 08:46:41

标签: asp.net-mvc-3 validationattribute

我希望MVC 3中的一些自定义验证属性仅在我提交时触发,而不是在输入失去焦点时触发。

这是我的自定义验证属性。

 #region Password Match Validation Attribute
    public sealed class PasswordPresent : ValidationAttribute, IClientValidatable
    {
        private const string _defaultErrorMessage = "Current Password no present";
        private string _basePropertyName;
        public PasswordPresent(string basePropertyName)
            : base(_defaultErrorMessage)
        {
            _basePropertyName = basePropertyName;
        }
        public override string FormatErrorMessage(string name)
        {
            return string.Format(_defaultErrorMessage, name, _basePropertyName);
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var basePropertyInfo = validationContext.ObjectType.GetProperty(_basePropertyName);
            var oldPassword =  (string)basePropertyInfo.GetValue(validationContext.ObjectInstance, null);
            var newPassword = (string)value;

            if (!string.IsNullOrEmpty(newPassword) && string.IsNullOrEmpty(oldPassword))
            {
                var message = FormatErrorMessage(validationContext.DisplayName);
                return new ValidationResult(message);
            }
            return null;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules
            (ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule();
            rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());

            //This string identifies which Javascript function to be executed to validate this 
            rule.ValidationType = "passwordpresent";
            rule.ValidationParameters.Add("otherfield", _basePropertyName);
            yield return rule;
        }
    }
    #endregion

这是客户端验证的.js文件

jQuery.validator.addMethod("passwordmatch", function (value, element, param) {

    if (value == null || value.length == 0) {
        return true;
    }
    return value == $(param).val(); ;

});


jQuery.validator.unobtrusive.adapters.add("passwordmatch", ["otherfield"], function (options) {
    options.rules["passwordmatch"] = "#" + options.params.otherfield;
    options.messages["passwordmatch"] = options.message;
});

这是我的模特

public class UserSettingsModel
    {

        [Display(Name = "Old Password")]
        [PasswordPresent("NewPassword",ErrorMessage = "Please enter in a New Password")]
        public string CurrentPassword { get; set; }

        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "New password")]
        public string NewPassword { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm new password")]
        [PasswordsMatch("NewPassword",ErrorMessage = "Confirm password and New Password do not match")]
        public string ConfirmPassword { get; set; }

    }

这是我的观点。

@model Data.Models.UserSettingsModel
   <div id="UserSettings">
 @using (Ajax.BeginForm("UpdateSettings", "AccountManagement", new AjaxOptions() {UpdateTargetId = "UserSettings", HttpMethod = "Post" }))
 {
        @Html.ValidationSummary(true)

        <div class="tabs" id="userTab3">
            <fieldset>
                <div>
                    <h3>
                        Change Password</h3>
                    <div class="editor-label">
                        @Html.LabelFor(model => model.CurrentPassword)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.CurrentPassword)
                        @Html.ValidationMessageFor(model => model.CurrentPassword)
                    </div>

                    <div class="editor-label">
                        @Html.LabelFor(model => model.NewPassword)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.NewPassword)
                        @Html.ValidationMessageFor(model => model.NewPassword)
                    </div>
                    <div class="editor-label">
                        @Html.LabelFor(model => model.ConfirmPassword)
                    </div>
                    <div class="editor-field">
                        @Html.EditorFor(model => model.ConfirmPassword)
                        @Html.ValidationMessageFor(model => model.ConfirmPassword)
                    </div>
                </div>

                <p>
                    <input type="submit" value="Save & Continue" name="btnsubmit" />
                </p>
            </fieldset>
        </div>
 }
 </div>

1 个答案:

答案 0 :(得分:1)

假设您正在使用jQuery Validate插件,您需要将其修改为仅绑定到提交按钮/表单提交。检查这个帖子:

jQuery validate rule ONLY AT SUBMIT