pTutorial

New way to learn Programming

Java Script checking for alphanumeric

JavaScript: Form validation- checking for alphanumeric (numbers and letters)

Sometime situations arise when web master wanted from the user to put number and character like (alpha numeric). You can write simple JavaScript function with the help of regular expression for this type of validation.

Regular Expression for alphanumeric

function checkAlphaNumeric(data) {
var letters = /^[a-zA-Z0-9\s]+$/;
if (data.match(letters)) {
return true;
} else {
return false;
}
}

To get only number and character in text field (0-9 and a-Z) with white space, we use regular expression for this validation (/^[a-zA-Z0-9\s]+$/) to allow alpha numeric in text field. This (^) sign indicate the starting and ($) sign indicate the end point,[[a-zA-Z0-9\s]+ means that any combination of number and character with space or without space.

Checking for alphanumeric example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/
libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$('#kk').click(function () {
var z = $.trim($('#uk').val());
if (checkAlphaNumeric(z)) {
$('#divData').html("You have enter " + " " + z);
$('#divData').css("color", "green");
return false;
} else {
$('#divData').html("Enter Alpha Numeric String Only");
$('#divData').css("color", "red");
return false;
}
})
});
function checkAlphaNumeric(data) {
var letters = /^[a-zA-Z0-9\s]+$/;
if (data.match(letters)) {
return true;
} else {
return false;
}
}
</script>
<style>
table{
border: 1px solid #080808;
margin: 5px;
padding: 10px;
}

</style>
</head>
<body>
<h4>Only alphanumeric is allowed</h4>

<table id="tab">
<tr>
</tr>
<tr>
<td>Enter Name *</td>
<td> <input type="text" id="uk" name="kk1"></td>
</tr>
<tr>
<td> <input type="submit" id="kk" value="Check"></td>
</tr>
</table>

<div id="divData"></div>
</body>
</html>

Download

See Also


QUOTES OF THE DAY

Saying is one thing, and doing is another.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER