我正在对某个字段进行一些验证。我首先运行Ajax GET来触发MVC操作结果,该结果将查明该字段是否有效。然后,我使用.addClass和.html在字段上方设置验证消息。发生的事情是验证消息显示在.html之后,但是一旦结束大括号传递(即函数退出)它就会消失。
为什么结束大括号会导致我的验证消息消失?
这是我的代码:
字段初始化(位于.js文件的顶部):
var $postalCode = $("#AccountBaseModel\\.Person\\.PostalCode");
在HTML中:
<div class="content-block__fourth-column">
@Html.LabelFor(x => x.AccountBaseModel.Person.PostalCode)
@Html.ValidationMessageFor(x => x.AccountBaseModel.Person.PostalCode)
@Html.TextBoxFor(x => x.AccountBaseModel.Person.PostalCode, new { id = "AccountBaseModel.Person.PostalCode", @class = "form-control" })
</div>
主要功能($ form.Submit):
$form.submit(function () {
//if not all the fields are entered (or the datestring is totally invalid) set it back to empty to cause validation
if ($date.val().match(dateRegEx) == null) {
$date.val("");
}
var usPostalValid = true;
var caPostalValid = true;
jQuery.ajaxSetup({ async: false });
if ($postalCode != null) {
$.get('/api/NCP/ValidatePostalCode', { postalCode: $postalCode.val() }, function (data) {
if (data.invalidUSPostal) {
usPostalValid = false;
}
if (data.invalidCAPostal) {
caPostalValid = false;
}
});
}
jQuery.ajaxSetup({ async: true });
clearErrorMessage($postalCode);
if (!usPostalValid) {
showErrorMessage($postalCode, 'Invalid US postal code.');
$form.data("isValid", false);
} else if (!caPostalValid) {
showErrorMessage($postalCode, 'Invalid CA postal code.');
$form.data("isValid", false);
} else {
$form.data("isValid", true);
}
//manually validate date and file field (because hidden)
var dateValid = $date.valid();
var promoCheck = checkDatePromo($form, $date, $year, $month, $day, $promoDateTime);
var fileValid = $file.valid();
return dateValid && promoCheck && fileValid && $form.valid() && (usPostalValid && caPostalValid);
});
clearErrorMessage():
function clearErrorMessage(element) {
var id = $(element).attr('id');
if (id.indexOf("ShippingPageModel") == 0) {
id = id.replace('_', '.');
}
$(element).closest('.form-group').find("span[data-valmsg-for='" + id + "']").removeClass('field-validation-error').addClass('field-validation-valid').html('');
}
showErrorMessage():
function showErrorMessage(element, message) {
var id = $(element).attr('id');
if (id.indexOf("ShippingPageModel") == 0) {
id = id.replace('_', '.');
}
var validationElement = $(element).closest('.form-group').find("span[data-valmsg-for='" + id + "']");
validationElement.removeClass('field-validation-valid').addClass('field-validation-error').html(message);
} // Once this line is finished executing, the validation message is gone..