首页 > 解决方案 > 如何在表单提交时通过 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”,然后避免表单提交。

提前非常感谢。

标签: javascriptjqueryregexspam

解决方案


我会使用一个覆盖所有西里尔语 unicode 范围的正则表达式范围:

let pattern  /[\u0400-\u04FF]/;
if (pattern.test("John Потоцкая Doe")) console.log("cyrillic");
else console.log("not cyrillic");

相关的 SO 问题

您的代码最终将如下所示:

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>


推荐阅读