c# - 在我的 asp.net 核心 MVC Web 应用程序中,我如何使 recaptcha 成为必填字段
问题描述
我正在开发一个 asp.net core mvc web 应用程序,并且我添加了以下字段以显示 google recaptcha 版本 2:-
<div class="form-group">
<div class="col-md-2"></div>
<div class="col-md-10">
<div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="@ViewData["ReCaptchaKey"]">
</div>
</div>
</div>
//code goes here
@section Scripts {
<script src='https://www.google.com/recaptcha/api.js'></script>}
在我的操作方法中,我正在检查用户是否选择了recaptcha,如下所示:-
public async Task<IActionResult> SearchNPI(ContactinfoCreate ci)
{
//add uncompleted entry
ViewData["ReCaptchaKey"] = _configuration.GetSection("GoogleReCaptcha:key").Value;
if (!ReCaptchaPassed(
Request.Form["g-recaptcha-response"], // that's how you get it from the Request object
_configuration.GetSection("GoogleReCaptcha:secret").Value,
_logger
))
{
ModelState.AddModelError(string.Empty, "Please enter CAPTCHA");
}
但是在客户端,我如何获取所需的recaptcha,所以用户不能提交表单,除非他/她选择recaptcha?
解决方案
可以通过触发recaptcha的data-callback方法判断是否在提交前点击recaptcha,然后添加一个隐藏控件。
点击recaptcha后,在data-callback方法中给隐藏控件赋值,然后judge the hidden value in the form submit method
判断这个表单是否可以提交。
<form method="post">
<div class="form-group">
<div class="col-md-2"></div>
<div class="col-md-10">
<div class="g-recaptcha" data-sitekey="@ViewData["ReCaptchaKey"]" data-callback="recaptchaCallback"></div>
<input type="hidden" value="" id="isClickCaptcha" />
<span class="text-danger" id="validationText"></span>
</div>
</div>
<input id="Submit1" type="submit" value="submit" />
</form>
<script src="https://www.google.com/recaptcha/api.js?hl=en-US"></script>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script>
var recaptchaCallback = function () {
$("#isClickCaptcha").val("yes");
};
$("form").submit(function () {
if ($("#isClickCaptcha").val() == "") {
event.preventDefault();
$("#validationText").text("Please enter CAPTCHA!");
return false;
}
})
</script>
推荐阅读
- javascript - 如何使用 react native firebase 将 6 位验证码发送到电子邮件以进行电子邮件验证?
- css - 带省略号和换行的多行截断
- windows - 如何在 WSL 上安装 PyGears - Ubuntu 20.04 LTS
- c# - 在 Asp Net Core 3.1 中带有列表的“multipart/form-data”返回错误请求
- neo4j - 在 neo4j 中是否可以消除执行第一个查询实例所需的额外时间?
- javascript - 在前端拦截来自外部库的 Web 套接字调用?
- wolfram-mathematica - 为什么我可以通过 ?Global`* 找到 y'[x] 的值
- compilation - 转译器的编译单元的等效名称是什么?
- react-native - react-native-webview 中的地图,如何缩放?
- bash - 使用带有 `bash -c` 的子 shell 来 bash 负通配符