我正在使用 Ajax 调用检查数据库中是否存在输入值 -
<div class="form-group Centre">
<label asp-for="Input.CentreId"></label>
<input asp-for="Input.CentreId" class="form-control" id="CentreInput" />
<span asp-validation-for="Input.CentreId" class="text-danger" id="CentreError"></span>
</div>
我有以下ajax调用-
$("#CentreInput").on('change', function (event) {
var urlVal = $(location).attr('href') + "?handler=CheckCentre"
$.ajax({
type: "POST",
url: urlVal,
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
"CentreId": $("#CentreInput").val()
},
async: false,
success: function (response) {
debugger;
var $validator = $("#RegisterForm").validate();
if (response.message == 'Not Found') {
errors = { CentreInput: "Centre does not exist in database" };
/* Show errors on the form */
$validator.showErrors(errors);
}
else if (response.message == 'Success') {
$("#CentreNameInput").val() = response.centreName;
}
else {
alert(JSON.stringify(response));
}
},
failure: function (response) {
debugger;
alert(JSON.stringify(response));
},
error: function (response) {
debugger;
alert(JSON.stringify(response));
}
});
});
我已经尝试过按照上面的方法进行验证,但没有成功。 尝试添加失败类别,请参见下文 -
$("#CentreInput").addClass("input-validation-error");
$("#CentreError").addClass("field-validation-error");
$("#CentreError").val() = "Centre does not exist in database"
没用。
有人可以帮忙吗?
谢谢你
在您的代码中,您需要首先确定您的ajax版本,从jQuery 1.8开始,
async: false
与jqXHR($.Deferred)的使用已不推荐使用。
jQuery 3.0 版本后,更新了新的
done
和 fail
方法来替代之前的 success
、error
等方法。
如果想要自定义在span中显示的错误消息,那么可以在validate方法的初始化中添加
errorPlacement
选项来自定义错误消息的显示位置。以下是您可以用作参考的示例:
@model CentreViewModel
<form id="RegisterForm">
<div class="form-group Centre">
<label asp-for="Input.CentreId"></label>
<input asp-for="Input.CentreId" class="form-control" id="CentreInput" />
<span asp-validation-for="Input.CentreId" class="text-danger" id="CentreError"></span>
</div>
</form>
@section Scripts {
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script type="text/javascript">
$("#CentreInput").on('change', function (event) {
var urlVal = $(location).attr('href') + "CheckCentre";
$.ajax({
type: "POST",
url: urlVal,
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
"CentreId": $("#CentreInput").val()
},
})
.done(function (response) {
var $validator = $("#RegisterForm").validate({
errorPlacement: function (error, element) {
error.appendTo('#CentreError');
}
});
if (response.message == 'Not Found') {
var errors = {};
errors[$("#CentreInput").attr("name")] = "Centre does not exist in database";
$validator.showErrors(errors);
}
else if (response.message == 'Success') {
$("#CentreNameInput").val(response.centreName);
alert(JSON.stringify(response));
}
else {
alert(JSON.stringify(response));
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
alert("AJAX request failed: " + errorThrown);
});
});
</script>
}
方法:
[HttpPost]
[Route("CheckCentre")]
public IActionResult CheckCentre( CentreInputModel model)
{
if (ModelState.IsValid)
{
if (model.CentreId == 1)
{
return Json(new { message = "Success", centreName = "Example Centre" });
}
else
{
return Json(new { message = "Not Found", centreName = "Not Found Centre" });
}
}
else
{
return BadRequest(new { message = "Validation Failed", errors = ModelState });
}
}
当我传入的数据不存在时