我要执行以下Form
的操作Validation
。我有以下代码:
<form method="post" asp-action="actionName" asp-controller="controllerName" id="myForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="card">
...
<div class="row">
<div class="col-sm-6 m-t-20">
<div class="fg-line">
<label asp-for="Name" class="fg-label" for="name">Name</label>
<input asp-for="Name" class="form-control" id="name" name="name" required />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 m-t-20">
<div class="fg-line">
<label asp-for="Age" class="fg-label" for="age">Age</label>
<input asp-for="Age" class="form-control" id="age" name="age" required />
<span asp-validation-for="age" class="text-danger"></span>
</div>
</div>
</div>
...
</div>
</form>
<script src="~/js/app.js"></script>
@section Scripts{
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
<script type="text/javascript">
$('form').validate({
onfocusout: function (element) {
this.element(element);
},
messages: {
amount: 'Enter Name',
age: 'Enter Age',
},
highlight: function (element) {
$(element).closest('.input-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.input-group').removeClass('has-error');
$(element).closest('.input-group').addClass('has-success');
}
})
$(document).ready(function(){
if(@ViewBag.userId != null){
var userId = @ViewBag.userId;
}
</script>
}
当我尝试提交空白表单(不输入任何数据)时,我希望弹出警告消息。但是,我在该字段旁边没有看到任何消息。但是,我可以看到表单没有提交,并且光标提示我输入一些文本。我要去哪里错了?
答案 0 :(得分:1)
问题在于,没有与JavaScript代码同时评估剃刀代码。您必须先使用剃刀检查空值,然后再使用JS代码
@if(ViewBag.userId != null)
{
//your code
}