Try this:
/^[1-9]\d*$/
This check would make sure that the first character was any digit but "0", followed by zero or more of any digit.
This pattern requires a slightly different approach from what you have. Instead of examining the key
value, you want to do the test against the entire field value. If the current key press breaks the pattern match, it will block the associated character from being added to the value.
Only keystrokes that add a character that continues to match the pattern will be allowed to be added. In this case the pattern breaks down to:
^
- beginning of the value
[1-9]
- exactly one character, only the digits 1 through 9 are allowed
\d*
- zero or more of any digit (i.e., 0 through 9)
$
- end of the value
UPDATE:
Now that I've seen how you are binding it, you should be able to make a couple of updates to make it work. First, you need to pass the element that the validation is bound to. . . so, in your HTML, change this:
onkeypress='validate_numberonly(event)'
. . . to this:
onkeypress='validate_numberonly(this, event)'
Then, in your JS, you need to make two changes: 1) accept the new parameter, and 2) retrieve the value of the input and make it part of the regex chek:
function validate_numberonly(evt) {
. . .
if( !regex.test(key) ) {
. . .
. . . becomes, this:
function validate_numberonly(el, evt) {
. . .
if( !regex.test(el.value + key) ) {
. . .
Now, the code will only except number values that create a value that matches the regex pattern.
That being said . . .
This also blocks ALL non numeric characters . . . including "Backspace" and "Delete" (not to mention, the arrow key, "Home", "End", etc.), meaning that the user can no longer change a value, once they have entered it, without using the right-click menu of their mouse (or adding additional validation to allow those control key values that you want to still function).
It really would make much more sense to use the regex that I provided as a "final value" check that is triggered by the onchange
event, and provide an error message of some sort, prompting the user to enter only digits, with no leading "0"s.