这差点让我丧命。我从未在一个问题上浪费太多时间。 我有一个需要通过调用REST API进行验证的字段,因为它需要检查数据库中某些数据的存在。我遇到的问题是,即使对json api的调用返回false,调用validator.validate也会返回true。
这是代码(我使用Kendo MVC帮助器,但与该问题无关)
<div id="divValidator1">
<div class="form-group">
@Html.LabelFor(m => m.Email)
@(Html.Kendo().TextBoxFor(m => m.Email)
.HtmlAttributes(new { placeholder = "you@domain.com", type = "email", @class = "k-textbox required",data_bind="value: XXX" })
)
</div>
<footer class="col-xs-12 form-group text-right">
@(Html.Kendo().Button()
.Name("Next1")
.Content("Next")
.HtmlAttributes(new { @class = "k-primary", data_bind = "enabled: isEnabled" })
.Events(ev => ev.Click("onNextClick")))
</footer>
var kendoValid = $("#divValidator1").kendoValidator({
validateOnBlur: false,
rules: {
remote: function (input) {
if (input.val() == "" || !input.attr("data-val-remote-url")) {
return true;
}
if (input.attr("data-val-remote-recieved")) {
input.attr("data-val-remote-recieved", "");
return !(input.attr("data-val-remote"));
}
var url = input.attr("data-val-remote-url");
var postData = {};
postData[input.attr("data-val-remote-additionalfields").split(".")[1]] = input.val();
var validator = this;
var currentInput = input;
input.attr("data-val-remote-requested", true);
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(postData),
dataType: "json",
traditional: true,
async:false,
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data == true) {
input.attr("data-val-remote", "");
}
else {
input.attr("data-val-remote", false);
}
input.attr("data-val-remote-recieved", true);
// validator.validateInput(currentInput);
},
error: function () {
input.attr("data-val-remote-recieved", true);
validator.validateInput(currentInput);
}
});
return true;
}
},
messages: {
remote: function (input) {
return input.attr("data-val-remote");
}
}
}).data("kendoValidator");
var viewModel1 = kendo.observable({
XXX:null,
isEnabled: function () {
var self = this;
self.get("XXX");
var x = $("#divValidator1").data("kendoValidator");
console.log(x.validate());
}
});
kendo.bind($("#divValidator1"), viewModel1);
这是控制器
public ActionResult IsEmailJustPresent(string email)
{
var res = email == "something";
return Json(res, JsonRequestBehavior.AllowGet);
}
还有ViewModel
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
[Remote("IsEmailJustPresent", "Home")]
public string Email { get; set; }
}
我还使用了kendo.observable,以便可以基于验证值启用/禁用下一个按钮。
在isEnabled函数中,您看到我这样做var x = $(“#divValidator1”)。data(“ kendoValidator”);但它始终返回true(似乎仅检查必需的属性)。
要实现该解决方案,我从here开始
如果需要,我在git上创建了一个更复杂的示例,其中包含我在最终项目中需要的向导
答案 0 :(得分:0)
这行注释可能是问题所在吗?
// validator.validateInput(currentInput);
属性“ data-val-remote”是否设置正确?