rdelfin
rdelfin

Reputation: 816

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?

Upvotes: 0

Views: 643

Answers (4)

Jonathan M
Jonathan M

Reputation: 17451

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/

Upvotes: 1

Tats_innit
Tats_innit

Reputation: 34107

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

Upvotes: 1

Eswar Rajesh Pinapala
Eswar Rajesh Pinapala

Reputation: 4911

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

Upvotes: 1

charlietfl
charlietfl

Reputation: 171669

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');

Upvotes: 0

Related Questions