Text box to accept only positive and negative numbers with 2 decimals

Last post 09-25-2008 5:45 AM by Lance Zhang - MSFT. 2 replies.

Sort Posts:

  • Text box to accept only positive and negative numbers with 2 decimals

    09-22-2008, 11:11 AM
    • Member
      27 point Member
    • cplusplus1
    • Member since 01-27-2007, 2:28 PM
    • Posts 219

    I am looking for a javascript function to validate a text box entry, it should only allow positive or negative numbers with two decimals. in a button click event function call.

    Thank you very much for the helpful information. 

     

     

  • Re: Text box to accept only positive and negative numbers with 2 decimals

    09-22-2008, 11:21 AM
    Answer
    • Participant
      1,582 point Participant
    • mohanbrij
    • Member since 08-07-2008, 8:40 AM
    • Bangalore, India
    • Posts 258

    You can use the below given regular expresion in JavaScript to validate the string

    ^[+-]?([0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)([eE][+-]?[0-9]+)?$

    To know how to use regular expression in javascript you can read the below article

    http://www.devarticles.com/c/a/JavaScript/Regular-expressions-in-JavaScript/

    Please remember to click “Mark as Answer” on the post that helps you

    Best Regards
    Brij Mohan
    http://www.dotnetglobe.com
  • Re: Text box to accept only positive and negative numbers with 2 decimals

    09-25-2008, 5:45 AM
    Answer
    Hi cplusplus1
     
    Please try the following code, it only allow positive or negative numbers, and at most two two decimals:
      
     <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title></title>
    <script type="text/javascript">
    function validate()
    {
    	    var pattern = /^-?[0-9]+(.[0-9]{1,2})?$/; 
                var text = document.getElementById('textbox1').value;
                if (text.match(pattern)==null) 
                {
    		alert('the format is wrong');
                } 
    	    else
    	    {
    		alert('OK');
    	    }
    
    }
    
    </script>
    
    </head>
    <body style="font-family:Calibri">
    <input type='text' id='textbox1' />
    <input type='button' value='OK' onclick="validate();">
    </body>
    </html>
    
     

    If I’ve misunderstood the facing problem, please feel free to let me know.


     
    Thanks.
     

     

    Lance Zhang
Page 1 of 1 (3 items)