In this, I am going to share with you How to make an HTML input type as alphabets or Allow input box only alphabets.

HTML5 Validate text box as alphabets this can be used in many fields like Name, Last Name, Middle Name, or any field that only allow alphabets in there text box where numeric values are not allowed.

Here we have used two ways to achieved Alphabets in Input type.

  1. Using onkeypress Function
  2. Using keyup Function


NOTE: Using the Above function you need jQuery Plugins to implement this function.

First, we use the onkeypress Function to allowed Alphabets in Input Type.
Here is the code to make Input type as alphabets using onkeypress function.


 <head>
Html5 HTML FORM take only letters
 </head>
<body>
 
<h1>HTML5 Validate Input type alphabets Using Jquery onkeypress Function</h1>
</body>


As you can see in the above example we have used onkeypress function to make HTML form input type allow alphabets this is a simple and easy way to the achieved text box as alphabets but there is one problem in it.

If you try to copy an alphanumeric value and paste in the text box it will accept the value.
This is only a disadvantage by using onkeypress function of jQuery.


As you can see in above image i have copy an paste alphanumeric value in text box it will accept it.

2) Using Jquery Keyup Function

Below is our HTML code of allow Input type as alphabets.


  
 <head>
Html5 HTML FORM take only letters
 </head>
 <body>
 
<h1>HTML5 Validate Input type alphabets Using Jquery Keyup Function</h1>
</body>

Jquery keyup function code.
 <script type="text/javascript">

    $(document).ready(function () {
	$('.alphabets').keyup(function () {
	if($(this).val().trim()!=""){
	var regEx = /^[a-zA-Z ]+$/i;
	  var val = $(this).val();
	  
	  if (val.trim()!=="" && !regEx.test(val.trim().replace(/^\s*|\s*$/g, ''))) {
		alert('Please enter only alphabets');
		$(this).val('');
	} }
	});
      
	});
	   </script>


The above function is to achieve an input type as alphabets.
As you can see we have used keyup function and regEx to make an input type only allow alphabet.

Source Code: GITHUB
HOPE THIS HELP YOU.

Post a Comment

أحدث أقدم