Friday, January 22, 2016

ASP.Net - Make textbox numeric only - easy way

Sometimes we try validating various types of input types such as numeric only, decimal numbers and many more. To avoid any crashes and run time errors, both client side as well as server side validation is important.

Numeric validation has made easy with JQuery now all you have to do is to download the js file and implement it on your web application. Let's see how it is done below; Make sure you reference a valid JQuery on top of your page.

 <script src="/js/numeric/jquery.numeric.js" type="text/javascript"></script>  

And your input will look like below;

 <asp:TextBox ID="txtId" runat="server" ClientIDMode="Static" CssClass="form-control"></asp:TextBox>  

And finally in your page related js file, add the following;

 $(document).ready(function () {  
   $("#txtId").numeric({ decimal: false, negative: false });  
 });  

The text box above will only enabled for entering positive whole numbers and no decimal is allowed. There are config parameters that we can use for different kind of numeric types such as;

 $("#txtId").numeric();  
 $("#txtId").numeric(","); // use , as separator  
 $("#txtId").numeric({ decimal : "," }); // use , as separator  
 $("#txtId").numeric({ negative : false }); // do not allow negative values  
 $("#txtId").numeric({ decimalPlaces : 2 }); // only allow 2 decimal places  
 $("#txtId").numeric(null, callback); // use default values, pass on the 'callback' function  

You can read more details here;

Happy coding :)

No comments:

Post a Comment