Wednesday, March 16, 2011

Some Usefull JavaScript Validations

Using of client side JavaScript is an efficient way to validate the user input in web applications. Here is some very useful and commonly used JavaScript form validations at one place.



1. Email Address Validation
function is_email(email) {
if(!email.match(/^[A-Za-z0-9\._\-+]+@[A-Za-z0-9_\-+]+(\.[A-Za-z0-9_\-+]+)+$/))
return false;
return true;
}
2. URL Validation
function is_valid_url(url){
var regexp = /[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/
return regexp.test(url);

}
3. US Phone Number Validation
function isPhoneNumber(str){
var re = /^\(?[1-9]\d{2}[\)\.-]?\s?\d{3}[\s\.-]?\d{4}$/

// alert(re.test(str));
return re.test(str);
}
4. Alphabets Only
function isAlpha(val)
{
var Alphabet =/^[A-Z a-z]+$/;
//A-Z or a-z Alphabets only allowed

var name = val;
if (name.search(Alphabet) == -1)
// Or
//if (!name.match(Alphabet))
{
return false;
}
else
{
return true;
}
}
5. Make String Uppercase
function makeUppercase(strname,strval)
{
document.getElementById(strname).value = strval.toUpperCase();
}
6. Upload Image Extension Validation
extArray = new Array("jpg", "gif", "jpeg","png");
function LimitAttach(file) {
allowSubmit = false;
var imgpath = file;
arr1 = imgpath.split("\\");
var len = arr1.length;
var img1 = arr1[len-1];
var chkval = img1.substring(img1.lastIndexOf(".")+1).toLowerCase();

for (var i = 0; i < extArray.length; i++) {

if (extArray[i] == chkval) { allowSubmit = true; break; }
}
if (allowSubmit)
return true;
else
return false;
}
7. Special Character Validation
function isSpclChar()
{
if (/[\\\/:*?;,"'&<>|!@#$%^(){}.+=\-_`~\[\]]/.exec(document.getElementById("name").value))
{
alert('Name can not contain special characters!');
document.getElementById('name').focus();
return false;
}
}
8. Space at start of string Validation
function isSpaceatStart(){
if(document.getElementById('firstname').value.indexOf(" ")==0)
{
alert('Invalid First name !');
document.getElementById('firstname').focus();
return false;
}
}
9. Remove White Space
function trim(str)
{
return str.replace(/^\s+|\s+$/, '');
}
10. Alphanumeric Validation
function is_alpha_numeric(str)
{
if(!str.match(/^[A-Za-z0-9 ]+$/))
return false;
return true;
}
11. Mobile Number Validation
function ToCellValidate()
{
cellno=document.form1.txtMobile.value
if(isNaN(cellno)||cellno.indexOf(" ")!=-1)
{
alert("Enter numeric value")
return false;
}
if (cellno.length>10 || cellno.length<10)
{
alert("enter 10 characters");
return false;
}
if (cellno.charAt(0)!="9")
{
alert("it should start with 9 ");
return false
}
}
12. Credit Card Validation
function checkCreditCard (cardnumber, cardname) {

// Array to hold the permitted card characteristics
var cards = new Array();

// Define the cards we support. You may add addtional card types.

//  Name:      As in the selection box of the form - must be same as user's
//  Length:    List of possible valid lengths of the card number for the card
//  prefixes:  List of possible prefixes for the card
//  checkdigit Boolean to say whether there is a check digit

cards [0] = {name: "Visa",
length: "13,16",
prefixes: "4",
checkdigit: true};
cards [1] = {name: "MasterCard",
length: "16",
prefixes: "51,52,53,54,55",
checkdigit: true};
cards [2] = {name: "DinersClub",
length: "14,16",
prefixes: "300,301,302,303,304,305,36,38,55",
checkdigit: true};
cards [3] = {name: "CarteBlanche",
length: "14",
prefixes: "300,301,302,303,304,305,36,38",
checkdigit: true};
cards [4] = {name: "AmEx",
length: "15",
prefixes: "34,37",
checkdigit: true};
cards [5] = {name: "Discover",
length: "16",
prefixes: "6011,650",
checkdigit: true};
cards [6] = {name: "JCB",
length: "15,16",
prefixes: "3,1800,2131",
checkdigit: true};
cards [7] = {name: "enRoute",
length: "15",
prefixes: "2014,2149",
checkdigit: true};
cards [8] = {name: "Solo",
length: "16,18,19",
prefixes: "6334, 6767",
checkdigit: true};
cards [9] = {name: "Switch",
length: "16,18,19",
prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
checkdigit: true};
cards [10] = {name: "Maestro",
length: "12,13,14,15,16,18",
prefixes: "5018,5020,5038,6304,6759,6761",
checkdigit: true};
cards [11] = {name: "VisaElectron",
length: "16",
prefixes: "417500,4917,4913",
checkdigit: true};

// Establish card type
var cardType = -1;
for (var i=0; i<cards.length; i++) {

// See if it is this card (ignoring the case of the string)
if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
cardType = i;
break;
}
}

// If card type not found, report an error
if (cardType == -1) {
ccErrorNo = 0;
return false;
}

// Ensure that the user has provided a credit card number
if (cardnumber.length == 0)  {
ccErrorNo = 1;
return false;
}

// Now remove any spaces from the credit card number
cardnumber = cardnumber.replace (/\s/g, "");

// Check that the number is numeric
var cardNo = cardnumber
var cardexp = /^[0-9]{13,19}$/;
if (!cardexp.exec(cardNo))  {
ccErrorNo = 2;
return false;
}

// Now check the modulus 10 check digit - if required
if (cards[cardType].checkdigit) {
var checksum = 0;                                  // running checksum total
var mychar = "";                                   // next char to process
var j = 1;                                         // takes value of 1 or 2

// Process each digit one by one starting at the right
var calc;
for (i = cardNo.length - 1; i >= 0; i--) {

// Extract the next digit and multiply by 1 or 2 on alternative digits.
calc = Number(cardNo.charAt(i)) * j;

// If the result is in two digits add 1 to the checksum total
if (calc > 9) {
checksum = checksum + 1;
calc = calc - 10;
}

// Add the units element to the checksum total
checksum = checksum + calc;

// Switch the value of j
if (j ==1) {j = 2} else {j = 1};
}

// All done - if checksum is divisible by 10, it is a valid modulus 10.
// If not, report an error.
if (checksum % 10 != 0)  {
ccErrorNo = 3;
return false;
}
}  

// The following are the card-specific checks we undertake.
var LengthValid = false;
var PrefixValid = false;
var undefined;

// We use these for holding the valid lengths and prefixes of a card type
var prefix = new Array ();
var lengths = new Array ();

// Load an array with the valid prefixes for this card
prefix = cards[cardType].prefixes.split(",");

// Now see if any of them match what we have in the card number
for (i=0; i<prefix.length; i++) {
var exp = new RegExp ("^" + prefix[i]);
if (exp.test (cardNo)) PrefixValid = true;
}

// If it isn't a valid prefix there's no point at looking at the length
if (!PrefixValid) {
ccErrorNo = 3;
return false;
}

// See if the length is valid for this card
lengths = cards[cardType].length.split(",");
for (j=0; j<lengths.length; j++) {
if (cardNo.length == lengths[j]) LengthValid = true;
}

// See if all is OK by seeing if the length was valid. We only check the
// length if all else was hunky dory.
if (!LengthValid) {
ccErrorNo = 4;
return false;
};   

// The credit card is in the required format.
return true;
}

function expired( month, year ) {
var now = new Date();                     // this function is designed to be Y2K compliant.
var expiresIn = new Date(year,month,0,0,0);  // create an expired on date object with valid thru expiration date
expiresIn.setMonth(expiresIn.getMonth()+1); // adjust the month, to first day, hour, minute & second of expired month
if( now.getTime() < expiresIn.getTime() ) return false;
return true;               // then we get the miliseconds, and do a long integer comparison
}

No comments:

Post a Comment