gpt4 book ai didi

c# - bool 字段的非侵入性客户端验证在 ASP.NET Core MVC 中不起作用

转载 作者:行者123 更新时间:2023-12-05 07:30:30 26 4
gpt4 key购买 nike

我在 ASP.NET Core 中发现了一个非常有趣的问题。我将我的 bool 字段用于复选框。我想强制用户选中要提交的表单的复选框。

我的模型类中的这个 bool 字段是:

[Range(typeof(bool), "true", "true", ErrorMessage = "You must accept the Terms")]
public bool TermsAccepted { get; set; }

注意我已经应用了 [Range] 验证属性。它完美服务器端验证

我的操作方法代码相当简单:

[HttpPost]
public IActionResult Index(JobApplication jobApplication)
{
if (ModelState.IsValid)
return View("Accepted", jobApplication);
else
return View();
}

But the problem is happening when I apply client side validation

在我看来,我应用了 3 个脚本:

@section scripts {
<script src="/lib/jquery/dist/jquery.min.js"></script>
<script src="/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js">
</script>
}

客户端验证的工作方式完全相反,当我选中复选框时它会给出错误消息。为什么会发生相反的情况?

复选框生成的 HTML 代码是:

<input type="checkbox" class="input-validation-error" data-val="true" data-val-range="You must accept the Terms" data-val-range-max="True" data-val-range-min="True" data-val-required="The TermsAccepted field is required." id="TermsAccepted" name="TermsAccepted" value="true" aria-describedby="TermsAccepted-error">

请帮忙?

最佳答案

我遇到了这个问题,你的代码添加了一些就没问题了......

我更新到最新版本的 jquery.validate (1.19.1) 和 jquery.validation.unobtrusive (3.2.11),(使用 libman 来管理这些依赖项)。

我还添加了这个 javascript block 来扩展该页面上验证器方法的功能。

 <script>
// extend range validator method to treat checkboxes differently
var defaultRangeValidator = $.validator.methods.range;
$.validator.methods.range = function(value, element, param) {
if(element.type === 'checkbox') {
// if it's a checkbox return true if it is checked
return element.checked;
} else {
// otherwise run the default validation function
return defaultRangeValidator.call(this, value, element, param);
}
}
</script>

关于c# - bool 字段的非侵入性客户端验证在 ASP.NET Core MVC 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52234747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com