我的问题是当第一次加载页面时,会弹出警报(1)和警报(2),但是当我点击我的保存按钮警报(3)时,不会弹出但是会显示验证消息(不会t meter如果我填写正确或错误我的下拉列表)并保存所有内容。 我有这种JS:
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
alert(1);
PassWayValidators();
$('#documents_TravelDocumentDocumentPass_PassDate').datepicker();
});
function PassWayValidators() {
alert(2);
$.validator.addMethod('PassWayValidator',
function (value, element) {
alert(3);
}, 'Please Inert Valid Numbers');
$("#documents_TravelDocumentDocumentPass_PassWayId").rules("add", {
PassWayValidator: true
});
}
</script>
<...Some Code Here...>
<div class="TravelDocumentDocumentPassCommentInner">
<span>გადაცემის ფორმა
<br />
@Html.DropDownListFor(model => documents.TravelDocumentDocumentPass.PassWayId, (IEnumerable<SelectListItem>)ViewBag.DocumentPassTypeList, String.Empty, isDisabled)
@Html.ValidationMessageFor(model => documents.TravelDocumentDocumentPass.PassWayId, "*")
</span>
</div>
<...Some Code Here too... and>
@Html.ValidationSummary()
谁能告诉我这是什么问题?
答案 0 :(得分:0)
由于您正在编写自定义验证器,因此我发现有两件事情需要纠正。
首先,您需要在$(document).ready()之外调用PassWayValidators();
。我不是100%确定它是必要的,但我认为这是我能够使自定义验证工作的唯一方式。
PassWayValidators();
$(document).ready(function () {
$('#documents_TravelDocumentDocumentPass_PassDate').datepicker();
});
然后,您需要配置下拉列表以确保它通过指定某些html属性来调用验证函数。
@Html.DropDownListFor(model =>
documents.TravelDocumentDocumentPass.PassWayId,
(IEnumerable<SelectListItem>)ViewBag.DocumentPassTypeList,
String.Empty,
new {
data_val = "true",
data_val_PassWayValidator = "Please insert valid numbers"
})
这样的事情。我不知道是什么规则(“add”{}),但我不确定你是否需要它。如果我错过了某些内容,这里是从我的一个应用程序中获取的完整示例。
<!-- some form and other html and stuff -->
@Html.TextBox("Amount", null, new
{
data_val = "true",
data_val_required = "This field is required",
data_val_number = "The field must be a number",
data_val_notBeZero = "Value must not be zero"
})
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
<script type="text/javascript">
// validators
$.validator.addMethod("notBeZero", function (value, element)
{
if (Number(Math.abs(value).toFixed(2)) == 0)
{
return false;
}
return true;
}, "Value must not be zero");
$.validator.unobtrusive.adapters.addBool("notBeZero");
</script>