I'm trying to get my login form to only validate if only numbers were inputted. I can it to work if the input is only digits, but when i type any characters after a number, it will still validate etc. 12akf will work. 1am will work. How can i get past this?
Part of the Login
<form name="myForm">
<label for="firstname">Age: </label>
<input name="num" type="text" id="username" size="1">
<input type="submit" value="Login" onclick="return validateForm()">
function validateForm()
{
var z = document.forms["myForm"]["num"].value;
if(!z.match(/^\d+/))
{
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
Using the form you already have:
This will delete all non-digits after the key is released.
If you are using React, just do:
Match against
/^\d+$/
.$
means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.Edit:
RobG wisely suggests the more succinct
/\D/.test(z)
. This operation tests the inverse of what you want. It returnstrue
if the input has any non-numeric characters.Simply omit the negating
!
and useif(/\D/.test(z))
.Late answer,but may be this will help someone
Use will be like
This ans was found from here with huge vote
Validate numbers in JavaScript - IsNumeric()
The simplest solution.
Thanks to my partner that gave me this answer.
You can set an onkeypress event on the input textbox like this:
onkeypress="validate(event)"
and then use regular expressions like this:
It will scan and remove any letter or sign different from number in the field.
I think we do not accept long structure programming we will add everytime shot code see below answer.