javascript - 如何在表单提交时通过 jQuery 阻止 Cyrillic unicode
问题描述
在我的网站上,我收到了一些订阅垃圾邮件。他们都来自使用俄语字母输入名字的人。
我知道在这种情况下,最推荐的做法是在我的订阅页面表单中添加验证码。但是,由于这种情况非常具体,同时我不想影响我的真实客户体验,我第一次想要一个 jQuery 脚本,当在某些输入中检测到俄语字母时拒绝提交表单. 有人可以帮我吗?(或者使用 PHP 更好?)
<form action="#" id="form-validate">
<input type="text" class="input" id="firstname">
<button class="submit">teste</button>
</form>
更加具体。例如,一个脚本在输入字符串中检测到一个西里尔字符,例如:“John Потоцкая Doe”,然后避免表单提交。
提前非常感谢。
解决方案
我会使用一个覆盖所有西里尔语 unicode 范围的正则表达式范围:
let pattern /[\u0400-\u04FF]/;
if (pattern.test("John Потоцкая Doe")) console.log("cyrillic");
else console.log("not cyrillic");
您的代码最终将如下所示:
let pattern = /[\u0400-\u04FF]/;
$(document).ready(function() {
$('#form-validate').submit(function() {
if (pattern.test($('input#firstname').val())) { //If "input" contains a Cyrillic character...
alert('Invalid input: please use Latin characters only.'); // pop alert message
$('input#firstname').val("") // empty field of invalid contents
return false; // prevent form from submitting
} else
return true; // allow form to be submitted
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" id="form-validate">
<input type="text" class="input" id="firstname">
<button class="submit">teste</button>
</form>
推荐阅读
- wordpress - 在 wordpress 中制作“滚动”地图
- java - Spring Boot 在控制器的每个操作中添加 if 语句
- javascript - 测试库 (VueJS) - 在 it 块中渲染多个组件
- java - 使用 Spring Boot Rest Template 给出 java.lang.NoClassDefFoundError: Could not initialize class sun.net.www.protocol.http.HttpURLConnection
- javascript - 文本索引到 Html 索引
- google-cloud-platform - 在 GCP 中,GSR 是他们无论如何我们可以将一个存储库限制为一个 IAM 用户?
- google-data-studio - 如何通过数据工作室中的用户输入匹配和过滤表
- visual-studio-2019 - 在项目根文件夹中找不到 deps.json 文件
- r - 重命名重复的行
- ios - 我的启动屏幕图像在小屏幕上的尺寸错误