Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)")         } } 
like image 797
Anthony Do Avatar asked May 23 '12 05:05

Anthony Do


People also ask

How do I allow only numbers in JavaScript?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.

How do you validate a number in JavaScript?

Approach: We have used isNaN() function for validation of the textfield for numeric value only. Text-field data is passed in the function and if passed data is number then isNan() returns true and if data is not number or combination of both number and alphabets then it returns false.

How do I verify a number only?

To check for all numbers in a field To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers. Next, the match() method of the string object is used to match the said regular expression against the input value.

How check input value is number or not in JavaScript?

In JavaScript, there are two ways to check if a variable is a number : isNaN() – Stands for “is Not a Number”, if variable is not a number, it return true, else return false. typeof – If variable is a number, it will returns a string named “number”.


1 Answers

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

like image 96
apsillers Avatar answered Oct 02 '22 02:10

apsillers