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:
You can also test the above regex here:
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!
~ Answered on 2012-03-21 06:23:18