validate email id, input only numbers, alphabets or alphanumeric characters

Refer to jquery code below to validate numeric, alphabets, alphanumeric and validate email id fields.

Function below allows users to enter only numeric values in textbox. Regular expression is used to check if the input character is numeric or not. If it is not numeric character then the entered character will be ignored. We can just place an alert message for giving notification to user.

// Numbers only
$(function () {
$(#txtNumber).keyup(function () {
if (this.value.match(/[^0-9]/g)) {
this.value = this.value.replace(/[^0-9]/g, ”);
}
});

Similarly, function below allows to enter only alphabets.

// Alphabets only
$(‘#txtAlphabet’).keyup(function () {
if (this.value.match(/[^a-zA-Z]/g)) {
this.value = this.value.replace(/[^a-zA-Z]/g, ”);
}
});

// Alphaneumeric characters only
$(#txtAlphaNeumeric).keyup(function () {
if (this.value.match(/[^a-zA-Z0-9]/g)) {
this.value = this.value.replace(/[^a-zA-Z0-9]/g, ”);
alert(“Enter only alphanumeric characters.”)
}
});
});

If we consider a textbox with an ID of txtEmail, following lines of code will apply client side validation on the textbox for email address, i.e the entered value in the textbox should be a valid email address, otherwise an alert message will be displayed.

Validate e-mail address
var txtEmail = document.getElementById(‘<%= txtEmail.ClientID %>’);
if (txtEmail .value != ”) {
var EmailRegEx = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!EmailRegEx.test(txtEmail .value)) {
alert(“Please enter valid email id!”)
txtEmail .focus()
return false;
}
}

Advertisements

About Gokul Dahal, Nepal

Software Engineer, Freelancer, Design and Develop web applications,Software Developer Nepal, FreeLancer Nepal Contact : gokuldahal@gmail.com
This entry was posted in C#, Javascript and Jquery and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s