我完全按照Darin Dimitrov提供的NotEqual属性实现了: https://stackoverflow.com/a/5742494/1946707
我遇到的问题是我正在使用jQuery对话框,并希望在对话框的客户端获得验证。我的必要验证已触发,但不相等的验证在客户端无效...任何帮助都将不胜感激。
这是我的模特:
public class ChangePasswordModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[NotEqual("OldPassword", ErrorMessage = "should be different than Prop1")]
[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")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
以下是我的观点:
@using (Html.BeginForm("ChangePassword", "Account", new { area = "" }, FormMethod.Post, new { id = "changePasswordForm" }))
{
<a href="#" onclick="openChangePasswordDialog();">Change Password</a>
<div id="dialogChangePassword" title="Change Password">
<table>
<tr>
<td>@Html.LabelFor(m => m.OldPassword)
</td>
<td>@Html.PasswordFor(m => m.OldPassword)
</td>
<td>@Html.ValidationMessageFor(m => m.OldPassword)
</td>
</tr>
<tr>
<td>@Html.LabelFor(m => m.NewPassword)
</td>
<td>@Html.PasswordFor(m => m.NewPassword)
</td>
<td>@Html.ValidationMessageFor(m => m.NewPassword)
</td>
</tr>
<tr>
<td>@Html.LabelFor(m => m.ConfirmPassword)
</td>
<td>@Html.PasswordFor(m => m.ConfirmPassword)
</td>
<td>@Html.ValidationMessageFor(m => m.ConfirmPassword)
</td>
</tr>
</table>
</div>
}
这是我的javascript:
var changePasswordDialogId = '#dialogChangePassword';
var oldPasswordInput = '#changePasswordForm #OldPassword';
var newPasswordInput = '#changePasswordForm #NewPassword';
var confirmPasswordInput = '#changePasswordForm #ConfirmPassword';
$(document).ready(function () {
$(changePasswordDialogId).dialog(
{
autoOpen: false,
autoResize: true,
modal: true,
open: function () {
$(this).parent().appendTo("#changePasswordForm");
},
buttons: {
Ok: function () {
if ($(oldPasswordInput).valid() && $(newPasswordInput).valid() && $(confirmPasswordInput).valid()) {
alert('ready to post!');
$(changePasswordDialogId).dialog('close');
}
},
Cancel: function () {
$(changePasswordDialogId).dialog('close');
}
}
});
}); //document.ready
function openChangePasswordDialog() {
$(changePasswordDialogId).dialog('open');
}
答案 0 :(得分:0)
似乎您忘记注册验证适配器
jQuery.validator.unobtrusive.adapters.add(
'notequalto', ['other'], function (options) {
options.rules['notEqualTo'] = '#' + options.params.other;
if (options.message) {
options.messages['notEqualTo'] = options.message;
}
});
Darin Dimitrov在答案中指出了这一点。
答案 1 :(得分:0)
好的,所以我发现了我的问题。我错过了IClientValidatable
的遗产
现在我已经添加了它,它可以在客户端工作,即使在我的jQuery对话框中也是如此。