Allow Only Numbers And Dot In Script


Answer :

This is a great place to use regular expressions.

By using a regular expression, you can replace all that code with just one line.

You can use the following regex to validate your requirements:

[0-9]*\.?[0-9]*

In other words: zero or more numeric characters, followed by zero or one period(s), followed by zero or more numeric characters.

You can replace your code with this:

function validate(s) {     var rgx = /^[0-9]*\.?[0-9]*$/;     return s.match(rgx); } 

That code can replace your entire function!

Note that you have to escape the period with a backslash (otherwise it stands for 'any character').

For more reading on using regular expressions with javascript, check this out:

  • http://www.regular-expressions.info/javascript.html

You can also test the above regex here:

  • http://www.regular-expressions.info/javascriptexample.html

Explanation of the regex used above:

  • The brackets mean "any character inside these brackets." You can use a hyphen (like above) to indicate a range of chars.

  • The * means "zero or more of the previous expression."

  • [0-9]* means "zero or more numbers"

  • The backslash is used as an escape character for the period, because period usually stands for "any character."

  • The ? means "zero or one of the previous character."

  • The ^ represents the beginning of a string.

  • The $ represents the end of a string.

  • Starting the regex with ^ and ending it with $ ensures that the entire string adheres to the regex pattern.

Hope this helps!


Use Jquery instead. Add a decimal class to your textbox:

<input type="text" class="decimal" value="" /> 

Use this code in your JS. It checks for multiple decimals and also restrict users to type only numbers.

$('.decimal').keyup(function(){     var val = $(this).val();     if(isNaN(val)){          val = val.replace(/[^0-9\.]/g,'');          if(val.split('.').length>2)               val =val.replace(/\.+$/,"");     }     $(this).val(val);  });​ 

Check this fiddle: http://jsfiddle.net/2YW8g/

Hope it helps.


Just add the code below in your input text:

onkeypress='return event.charCode == 46 || (event.charCode >= 48 && event.charCode <= 57)' 

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable