EDIT: OK, updated as per your comment, an expression to match either a lone minus sign or any combination of digits with no minus sign:
function IsNumeric(sText){
return /^(-|\d+)$/.test(sText);
}
If you want only positive numbers and don't want to allow leading zeros then use this regex:
/^(-|[1-9]\d*)$/
Regarding your question "any method to do the verification without using regex?", yes, there are endless ways to achieve this with the various string and number manipulation functions provided by JS. But a regex is simplest.
Your function returns true
if the supplied value contains any combination of digits and the plus or minus symbols, including repeats such as in "---+++123"
. Note that the +
towards the end of your regex means to match the preceding character 1 or more times.
What you probably want is a regex that allows a single plus or minus symbol at the beginning, followed by any combination of digits:
function IsNumeric(sText){
return /^[-+]?\d+$/.test(sText);
}
?
means match the preceding character 0 or 1 times. You can simplify [0-9]
as \d
. Note that you don't need the if
statement: just return the result from .test()
directly.
That will accept "-123", "123", "+123" but not "--123". If you don't want to allow a plus sign at the beginning change the regex to /^-?\d+$/
.
"example: 1,2,3,4,5,6,7,8,9,0 will return true and - will return true as well."
Your example seems to be saying that only a single digit or a single minus sign is considered valid - if so then try this:
function IsNumeric(sText){
return /^[\d-]$/.test(sText);
}