Saturday, October 20, 2012

Numeric Data validation in Javascript

To check whether a user-given number is numeric, we can test it with a regular expression pattern. 

Problem :: Suppose, on a webpage, there is a textbox where user needs to input valid numeric data. That data has to be greater than zero also. 

Solution :: We can write a javascript function as given below.

<script type='text/javascript'>
function test_numeric($data)
{
 // Define Regular Expression Pattern 
 var $pattern = /^[0-9]+(\.)?[0-9]+$/;

 // Test the pattern
 $result = $pattern.test( $data );

 // Input data is matching our expected pattern 
 if( $result ) 
 {
   // Now check if Data is Positive
   if( parseFloat( $data ) > 0 )
     return parseFloat( $data );
   else
     return 0;

 }
 // Input data does not match our expected pattern
 else 
 {
    return 0;  
 }
}
</script>

The above function returns the floating representation of input data when the Input data is valid or matches our given pattern. If it does not match the pattern, 0 is returned.

Now let's simplify the regular expression /^[0-9]+(\.)?[0-9]+$/ 
1. ^[0-9]+  => means the Input data should start with digits 0 to 9, 1 or more digits may appear.
2. (\.)?    => means the character dot (.) may or may not appear at all
3.  [0-9]+$  => means the input data ends with digit[0-9] sequence and may have 1 or more digits in it.

Another point, we need to discuss here. The above regular expression will pass "0009" as a valid input. That's why we have returned floating point representation of  the original number by using the statement :: 

return parseFloat( $data );

The above statement would return "9" if the input was "0009".

No comments: