• Register
100 points
7 4

We add input in a web page to get input from the user, there are so many different input tags like text, number and many more. Assuming we want to get only numbers as input from the user, we can use number input but the user can still use characters instead of numericals digits. To prevent that situation we are creating a program that tells the user to enter the only numericals digits if he enters any other characters.

Approach

If the user enters the characters other than number then the function will pop up an alert telling it to enter numbers only.

  1. Create a variable with only numericals characters.
  2. Now, we will use the match function to check the input.
  3. If the input is only numbers then show accepted otherwise show error.

Program

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - checking all numbers</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input your registration number and submit</h2>
<form name="form1" action="#">
<ul>
<li><input type='text' name='text1'/></li>
<li class="rq">*Enter numbers only.</li>
<li>&nbsp;</li>
<li><input type="submit" name="submit" value="Submit" onclick="allnumeric(document.form1.text1)" /></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script>
function allnumeric(inputtxt)
   {
      var numbers = /^[0-9]+$/;
      if(inputtxt.value.match(numbers))
      {
      alert('Your Registration number has accepted....');
      document.form1.text1.focus();
      return true;
      }
      else
      {
      alert('Please input numeric characters only');
      document.form1.text1.focus();
      return false;
      }
   } 

</script>
</body>
</html>

The javascript program checks if the input given by the user is only numbers or not by using the match() function.

 

Output

imageimage

Hope this will help.

100 points
7 4