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+]*$
}
1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

2 Comments

regex fails when the Textbox empty which i don't want
@AkhilJain Updated the code and now check
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.

Comments