简体   繁体   中英

Regex not working in jquery for form validation

I am runing the following jquery script:

<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>

The problem is that the p2 never gives me anything when I deselect the input. What did I do wrong?

You need to say:

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

instead of:

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

...because .match() returns an array if matched. See here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match

Here's a working version: http://jsfiddle.net/k45Ka/5/

Working demo http://jsfiddle.net/r4VPZ/3/ or http://jsfiddle.net/r4VPZ/4/

You can see .match explaination above.

You can also use .toString with .html or .text api. You can do a null handling or look into isNaN http://www.w3schools.com/jsref/jsref_isnan.asp

Hope it helps, please let me know if I missed anything, cheers :)

Good read: http://api.jquery.com/html/ & http://api.jquery.com/text/

Match : What does .match returns : learning regex and jquery - what does .match return?

code

$(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);​​

demo : http://jsfiddle.net/epinapala/TbCfc/

match returns null when the regex is not matched!

$(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);
  });
});

You aren't creating any text values to put in if test passes or fails

DEMO http://jsfiddle.net/9MJNj/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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