pTutorial

New way to learn Programming

Java Script checking for all letters

JQuery or JavaScript: Form validation - checking for all letters

Often situations arise when web master wanted from the user to put only single or more character (A-Z or a-z) with white space in the HTML field. You can write simple JavaScript function with the help of regular expression to validate the text field.

Regular Expression for all letter

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

To get single or more character with space (both uppercase or lowercase) we use a regular expression (/^[A-Za-z\s]+$/) which allows only letters with white space. The match method of string object is used to match the regular expression against the input value of text field.

Checking for all letters 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 (checkChar(z)) {
$('#kk').css("border-color", "green");
$('#divData').html("You have enter "+" " +z);
$('#uk').css("border-color", "green");
$('#tab').css("border-color", "green");
return false;
} else {
$('#kk').css("border-color", "red");
$('#uk').css("border-color", "red");
$('#divData').html("Please enter String Only");
$('#tab').css("border-color", "red");
return false;

}
})
});
function checkChar(data){
var letters = /^[a-zA-Z\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>Validation for letters only</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

Explanation

JQuery is used to notify the user to put only character in the text field with proper colour combination easily see the example.

See Also


QUOTES OF THE DAY

Knowledge itself is a power.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER