繁体   English   中英

正则表达式不适用于表单验证的jQuery

[英]Regex not working in jquery for form validation

我正在运行以下jquery脚本:

<html>
<head>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#textThing").blur(function(){
    var isNumber = $("#textThing").val().match(/^\d+/);

    $("#p2").html(isNumber);
  });
});

</script>

</head>

<body>
<input type="text" id="textThing" />
<p id="p2">Paragraph 2</p>
</body>
</html>

问题是,当我取消选择输入时,p2不会给我任何东西。 我做错了什么?

您需要说:

$("#p2").html(isNumber == null ? "" : isNumber[0]);

代替:

$("#p2").html(isNumber);

...因为.match()如果匹配则返回一个数组。 参见此处: https//developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match

这是一个工作版本: http : //jsfiddle.net/k45Ka/5/

工作演示 http://jsfiddle.net/r4VPZ/3/ http://jsfiddle.net/r4VPZ/4/

您可以在上方看到.match解释。

您还可以将.toString.html.text api结合使用。 您可以进行null处理,也可以查看isNaN http://www.w3schools.com/jsref/jsref_isnan.asp

希望对您有所帮助,如果我错过了任何事情,请告诉我,干杯:)

好的阅读: http : //api.jquery.com/html/ http://api.jquery.com/text/

Match.match返回什么: 学习正则表达式和jquery-.match返回什么?

$(document).ready(function(){
  $("#textThing").on("blur",function(){
    var isNumber = $("#textThing").val().match(/^\d+/);

     $("#p2").html(isNumber.toString());
    // $("#p2").text(isNumber);
  });
});

//var folioIsNumResult = $("#Folio").val().match(/^\d+/i);​​

演示: http : //jsfiddle.net/epinapala/TbCfc/

当不匹配正则表达式时,match返回null!

$(document).ready(function(){
  $("#textThing").blur(function(){
    var isNumber = $(this).val().match(/^\d+/);
      if(isNumber == null){
          var res = "not a number"
              }else{
              var res = "valid number";
              }
    $("#p2").html(res);
  });
});

如果测试通过或失败,您不会创建任何文本值

演示http://jsfiddle.net/9MJNj/

   $("#p2").html(isNumber ? 'Is number':'Is not');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM