My idea is something like this but I dont know the correct code
if (mystring.matches("[0-9.]+")){
//do something here
}else{
//do something here
}
I think I'm almost there. The only problem is multiple decimal points can be present in the string. I did look for this answer but I couldn't find how.
Use the test() method to check if a string contains only digits, e.g. /^[0-9]+$/. test(str) . The test method will return true if the string contains only digits and false otherwise.
The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False.
To check if a string contains numbers in JavaScript, call the test() method on this regex: /\d/ . test() will return true if the string contains numbers. Otherwise, it will return false .
If you want to -> make sure it's a number AND has only one decimal <- try this RegEx instead:
if(mystring.matches("^[0-9]*\\.?[0-9]*$")) {
// Do something
}
else {
// Do something else
}
This RegEx states:
Note that bullet point #2 is to catch someone entering ".02" for example.
If that is not valid make the RegEx: "^[0-9]+\\.?[0-9]*$"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With