Search code examples
javascriptvalidationnumbers

Javascript - validation, numbers only


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)")
        }
}

Solution

  • 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 returns true if the input has any non-numeric characters.

    Simply omit the negating ! and use if(/\D/.test(z)).