我正在为MVC应用程序实现自定义不干扰客户端JavaScript。当我按下“提交”按钮时,自定义验证方法([EnforceTrue]属性)会触发,但没有任何效果。在Submit事件中,尽管自定义方法返回了false值,但Form.valid()方法仍返回true。 (我将其硬编码为false)。
我已经阅读了有关Unovertrusive验证主题的Stackoverflow,发现了很多设计,选项,想法,建议等并没有真正帮助。我尝试通过nuget包引用代码库。我将代码移到了视图的顶部,而不是在底部。我使用更复杂的验证逻辑进行了尝试,但其行为仍然相同。最终,我将应用程序缩小为几行代码,以重现行为。
这是我的模型:提交之前,它包含一个必填的“名称”字段和一个需要选中的复选框。该复选框需要自定义验证。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection; // AtLeastOneProperty
using System.Web.Mvc; // Client side Validation STuff (26/08/19)
namespace WebApplication7_POC.Models
{
public class Consultant
{
[Required, Display(Name = "First name:"), MaxLength(80)]
public string FIRSTNAME { get; set; } // FIRSTNAME
[Display(Name = "I give my concent.")]
[EnforceTrue] // TEST 123
public bool Concent { get; set; } // AccessAdditional
}
public class EnforceTrueAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
if (value == null) return false;
if (value.GetType() != typeof(bool)) throw new InvalidOperationException("can only be used on boolean properties.");
return (bool)value == true;
}
public override string FormatErrorMessage(string name)
{
return "The '" + name + "' field must be checked in order to continue.";
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = String.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,
ValidationType = "enforcetrue"
};
}
}
}
下面是视图。它在顶部实现用于Custom验证的JQuery。在底部,它捕获了Submit事件,然后检查表单是否已验证。 valid()。
@model WebApplication7_POC.Models.Consultant
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
(function ($) {
// TEST 123
$.validator.addMethod("enforcetrue", function (value, element, param) {
alert('client validation trigerred!');
console.log(element);
console.log(element.checked);
return false; // element.checked;
});
$.validator.unobtrusive.adapters.addBool("enforcetrue");
}(jQuery));
</script>
@{
ViewBag.Title = "Consultant";
}
<h2>Consultant</h2>
@using (Html.BeginForm("Consultant","Home",FormMethod.Post,new { id = "HelloForm" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Consultant</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.FIRSTNAME, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FIRSTNAME, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FIRSTNAME, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Concent, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
@Html.EditorFor(model => model.Concent)
@Html.ValidationMessageFor(model => model.Concent, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Submit it!" class="btn btn-default" />
</div>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
<script type="text/javascript">
$(document).ready(function () {
$("#HelloForm").submit(function () {
alert('HelloForm submit trigerred');
// https://stackoverflow.com/questions/53934575/asp-net-core-unobtrusive-client-side-validation-form-onsubmit-fires-even-on-vali
if ($("#HelloForm").valid()) {
// Show the Spinner
alert('Valid!');
// Sure this works, but it does not validate the custon validation rules.
// $("#LoaderSpinner").show('hidden');
// $(".overlay").show();
} else {
alert('Not Valid');
}
});
});
</script>
有一个控制器可以处理回发,但是我的问题是进行客户端验证。
当按下提交按钮时,我希望当未选中复选框时,valid()方法将返回false,并在屏幕上显示错误消息(例如默认的[Required]属性正在执行)。
也许我这边只是一个疏忽之处?
答案 0 :(得分:0)
删除
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
第二次包含jquery的代码段最终解决了该问题。