1

I have a textbox and I want to check if it contains only numbers (with no space and Special Character) onblur I don;t know how to check the Regex alert should Comes if Regex fails

<asp:TextBox ID="txtFromDate" runat="server" placeholder="Contract ID" onblur="checkValue(this.value)">

//JS CODE
function checkValue(this) {
   //regex    ^[0-9+]*$
}
  • Also see [check if string contains only numbers, else show message](//stackoverflow.com/q/10380937) and [Check if a textbox contains numbers only](//stackoverflow.com/q/30323610) – Tushar Jul 03 '17 at 05:34

3 Answers3

1

Why not use NaN?

 //JS CODE
function checkValue(x) {
   return isNaN(x);
}

This will return true if the value is not a number, else false if its not.

Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
  • 1
    It's a good solution for checking numbers. But I think OP doesn't want dot `.` to be allowed. for Eg, `2.99` is not a `NaN` – Muthu Kumaran Jul 03 '17 at 04:01
0
<asp:TextBox ID="txtFromDate" runat="server" 
placeholder="Contract ID"> //Here you don't need any event as jquery automatically calls respective function when blur event occurs.


$("#txtFromDate").blur(function(){
   var reg = /^[0-9+]*$/;
   if (reg.test($("#txtFromDate").val())) {
      alert("Your number is valid.");
   }
   else{
      alert("Your number is not valid.");
   }
});

Hope it helps.

Muthu Kumaran
  • 17,682
  • 5
  • 47
  • 70
Chirag
  • 994
  • 2
  • 11
  • 26
0

You can use test to check regex against the input,

function checkValue(val){
  if(!val || /^\d+$/.test(val) === false){
   alert('Failed')
  }
}
<input type="text" onblur="checkValue(this.value)" />

If you want user are allowed to type only numeric data then refer this post, HTML Text Input allow only Numeric input

Muthu Kumaran
  • 17,682
  • 5
  • 47
  • 70