如果针对正则表达式的模式,则禁止继续在文本框上书写

时间:2017-12-02 06:03:24

标签: javascript jquery regex

我的护照代码textbox

如何定义用户输入的代码是否与正则表达式不同,以防止继续在文本框上书写?

并保持错误,直到用户输入正确的错误? 这是我的片段:

$(".passno").each(function(index, element) {
  $(this).bind('keyup', function(event) {
    var regex = new RegExp("^[A-Z][0-9]{8}$");
    var value = event.currentTarget.value;
    if (!regex.test(value)) {
      $(this).next(".box-infoes").find(".error").css("display", "block")
    } else {
      $(this).next(".box-infoes").find(".error").css("display", "none")
    }

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" class="passno" placeholder="e.g.=J12345678" />
<div class="box-infoes">
  <div style="color:red; display:none;" class="error"> This Is a Wrong passportcode !</div>
</div>

2 个答案:

答案 0 :(得分:1)

你的正则表达式应该像\,但你的代码需要更多的修改,这样可以防止计算一些按钮,如 SHIFT CTRL RegExp("[A-Z]{1}[0-9]{8}")字符或如果它为空,则删除错误等。

现在正则表示:AS只有一个字+ [A-Z]{1}八个数字。

示例类型 J12345678

[0-9]{8}
$(".passno").each(function(index, element) {
  $(this).bind('keyup', function(event) {
    var regex = new RegExp("[A-Z]{1}[0-9]{8}");
    var value = event.currentTarget.value;
    $(this).val($(this).val().toUpperCase());
    
    if (!regex.test(value) || value.length > 9) {
      $(this).next(".box-infoes").find(".error").css("display", "block")
    } else {
      $(this).next(".box-infoes").find(".error").css("display", "none")
    }

  });
});

嗯,对于限制字符长度,您可以使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <input type="text" class="passno" placeholder="e.g.=J12345678" maxlength="9"/> <div class="box-infoes"> <div style="color:red; display:none;" class="error"> This Is a Wrong passportcode !</div> </div>上的maxlength="9"或使用input jquery

来控制它

答案 1 :(得分:0)

$(".passno").each(function(index, element) {
  $(this).bind('keypress', function(event) {
    var regex = new RegExp("^[A-Z][0-9]{8}$");
    var value = event.currentTarget.value;
    if (!regex.test(value)) {
      $(this).next(".box-infoes").find(".error").css("display", "block");
       event.preventDefault();
    } else {
      $(this).next(".box-infoes").find(".error").css("display", "none")
    }

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" class="passno" placeholder="e.g.=J12345678" />
<div class="box-infoes">
  <div style="color:red; display:none;" class="error"> This Is a Wrong passportcode !</div>
</div>