There are many situations when you need to validate entered data in HTML forms with jQuery.
We created several examples that are most used among web developers so please find it below. If you have any other suggestion that we could write about please contact us as let us know.
- Advertisement -
For the beginning here are the main HTML and jQuery code:
<input id="testfield" type="text" />
// Check entered value on field leaving
$(document).ready(function() {
// Field lost focus
$('#testfield').blur(function(){
// Get entered value
var data = $('#testfield').val();
// Validate phone number
if(validatePhoneNumber(data)) {
alert('Entered data is an valid email address.');
}
// Validate User Id
if(validateUserName(data)) {
alert('Entered data is an valid email address.');
}
// Validate Date
if(validDate(data)) {
alert('Entered data is an valid email address.');
}
// Validate email address
if(validEmailAddress(data)) {
alert('Entered data is an valid email address.');
}
});
});
- Advertisement -
- Advertisement -
Phone Numbers Validation
The following function could be used for phone number validation:
/**
* Function validates phone number
*
*/
function validatePhoneNumber(data) {
var pattern=new RegExp(/^[0-9-+]+$/);
return pattern.test(data);
}
User Name Validation
You can need use this method to validate user names or id allowing only alpha-numerical characters and underscores
/**
* Function validates user name. Allowed characters are alpha-numerals and underscores
*
*/
function validateUserName(data) {
var pattern= new RegExp(/^[a-z0-9_]+$/);
return pattern.test(data);
}
- Advertisement -
Date Validation
The following method checks whether passed value is a valid date
/**
* Function validates date
*
*/
function validateDate(data) {
var pattern= new RegExp(/\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/);
return pattern.test(data);
}
Email Address Validations
Validating email address with jQuery is one of the most needed function
/**
* Function validates email
*
*/
function validateEmail(data) {
var pattern= new RegExp(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]+$/);
return pattern.test(data);
}
- Advertisement -