What if you want to validate a string with a floating point number without any other characters in it except minus (-) sign. You can use multiple if/switch statement but the code goes long way down
to cater for all invalid characters (such as * & $ £).
Regular Expression comes to the rescue. Lets take the following example.
e.g
Valid numbers
0.45, -0.33, -34, 100, 0, -3.44
Invalid numbers
$3, +6.55, --56, 46*, 33"!, &, +88
Regular Expression = (^-?\d{1,3}\.?\d{0,5}?$)
Explanations:
^-? == ^ sign means match the string starting with. ? (question mark) means optional. The string means match the string that starts with an optional minus sign. This mean string starts with "-2" and "2" are valid. "+2", "@%£2" are invalid.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment