Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (7k points)

I am trying to get my login form to validate if only numbers were inputted. It works when all the values are digits but also when characters after a number. How can I get past this?

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

        }

}

1 Answer

0 votes
by (13.1k points)

In your match method put /^\d+$/ . Here, $ means “end of the line”, so any non-digit characters after the initial run of digits will cause the match to fail.

You can also use /\D/.test(z) . This operation tests the inverse of what you wait for. It returns true if the input has any non-numeric characters. Simply omit the ! and use if(/\D/.test(z))

Want to learn full stack development? Check out the full stack developer course from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Feb 25, 2021 in Web Technology by Jake (7k points)
0 votes
1 answer
0 votes
1 answer
asked Feb 22, 2021 in Web Technology by Jake (7k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...