我有两个带有值的选择输入,我正在尝试进行验证。
如果第二个选择的值等于第一个选择的值,则应弹出一条消息以更改该值。
我尝试使用$.validator
,但仍然无法使其正常工作。
$('#SubstituteUserGid').change(function () {
$('#mainForm').validate({
rules: {
SubstituteUserGid: { notEqual: userName }
}
});
});
jQuery.validator.addMethod("notEqual", function (value, element, param) {
return this.optional(element) || value != param;
}, "Please specify a different (non-default) value");
这是HTML
<select asp-for="UserGid" data-val-required="Моля изберете служител"
placeholder="Моля изберете служител" class="form-control" data-val="true">
@foreach (var user in Model.AllActiveUsers)
{
<option value="@user.Gid" data-balance="@user.Balance">@user.Name</option>
}
</select>
<select asp-for="SubstituteUserGid" class="form-control" data-val="true">
<option value="">-- Без заместващ --</option>
@foreach (var user in Model.AllActiveUsers)
{
<option value="@user.Gid">@user.Name</option>
}
</select>
答案 0 :(得分:0)
最好使用Remote
属性,这将大大满足您的目的。
按如下方式说您的模型类:
public class Foo
{
public string UserGid {get; set;}
[Remote(action: "IsUserGuidEquals", controller: "Validation",AdditionalFields = "UserGid", ErrorMessage = "UserId are equals! Please select different one!")]
public string SubstituteUserGid {get; set;}
}
然后在控制器中的IsUserGuidEquals
方法中,如下所示:
public class ValidationController : Controller
{
public JsonResult IsUserGuidEquals(string substituteUserGid, string userGid)
{
return Json(substituteUserGid != userGid,JsonRequestBehavior.AllowGet);
}
}
答案 1 :(得分:0)
您的代码运行正常,添加与activeuser相同的类,然后重试,
<select asp-for="UserGid" data-val-required="Моля изберете служител"
placeholder="Моля изберете служител" class="form-control activeuser" data-val="true">
@foreach (var user in Model.AllActiveUsers)
{
<option value="@user.Gid" data-balance="@user.Balance">@user.Name</option>
}
</select>
<select asp-for="SubstituteUserGid" class="form-control activeuser" data-val="true">
<option value="">-- Без заместващ --</option>
@foreach (var user in Model.AllActiveUsers)
{
<option value="@user.Gid">@user.Name</option>
}
</select>
$('#SubstituteUserGid').change(function () {
$('.activeuser').validate({
rules: {
SubstituteUserGid: { notEqual: userName }
}
});
});
jQuery.validator.addMethod("notEqual", function (value, element, param) {
return this.optional(element) || value != param;
}, "Please specify a different (non-default) value");