Given an input element and the task is to check whether the input element is alphanumeric or not. There are two methods to solve this problem which are discussed below:
Approach 1:
- A RegExp is used to validate the input.
- RegExp is used to check the string of invalid characters which doesn’t contain (a-z) alphabets and all numeric digits to validate.
- A not operator is used for desired output.
Example 1: This example implements the above approach.
<!DOCTYPE HTML> < html >
< head >
< title >
How to validate an input is alphanumeric
or not using JavaScript?
</ title >
</ head >
< body align = "center" >
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< p id = "GFG_UP" style =
"font-size: 15px; font-weight: bold;" >
</ p >
< form id = "formElement" >
Input: < input id = "input1" type = "text" />
</ form >
< br >
< button onclick = "GFG_Fun()" >
click here
</ button >
< p id = "GFG_DOWN" style =
"font-size: 24px; font-weight: bold; color:green;" >
</ p >
< script >
var el_up = document.getElementById('GFG_UP');
var el_down = document.getElementById('GFG_DOWN');
var input = document.getElementById('input1');
el_up.innerHTML = "Click on the button to "
+ "validate alphanumeric input.";
function GFG_Fun() {
var val = input.value;
var RegEx = /[^a-z\d]/i;
var Valid = !(RegEx.test(val));
el_down.innerHTML = Valid;
}
</ script >
</ body >
</ html >
|
Output:
-
Before clicking on the button:
-
After clicking on the button:
Approach 2:
- A different RegExp is used to validate the input.
- RegExp is checking for the (a-z) alphabets and (0-9) digits to validate.
Example 2: This example implements the above approach.
<!DOCTYPE HTML> < html >
< head >
< title >
JavaScript | Validate If input is alphanumeric or not?
</ title >
</ head >
< body id = "body" align = "center" >
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< p id = "GFG_UP" style =
"font-size: 15px; font-weight: bold;" >
</ p >
< form id = "formElement" >
Input: < input id = "input1" type = "text" />
</ form >
< br >
< button onclick = "GFG_Fun()" >
click here
</ button >
< p id = "GFG_DOWN" style =
"font-size: 24px; font-weight: bold; color:green;" >
</ p >
< script >
var el_up = document.getElementById('GFG_UP');
var el_down = document.getElementById('GFG_DOWN');
var input = document.getElementById('input1');
el_up.innerHTML = "Click on the button to "
+ "validate alphanumeric input.";
function GFG_Fun() {
var val = input.value;
var RegEx = /^[a-z0-9]+$/i;
var Valid = RegEx.test(val);
el_down.innerHTML = Valid;
}
</ script >
</ body >
</ html >
|
Output:
-
Before clicking on the button:
-
After clicking on the button:
Article Tags :
Recommended Articles
1. How to validate if input in input field has alphanumeric characters only using express-validator ?
3. How to validate if input in input field exactly equals to some other value using express-validator ?