Monday, March 9, 2009

Javascript form validation



Folder Structure
------->form_validation
|----->css
css/messages.css
css/style.css
|----->scripts
scripts/messages.js
|----->images
msg_arrow.gif
|----->jsvalidationdemo.php

/************************messages.css**************************/

/** {margin:0; padding:0}*/
/*body {font:12px Verdana, Arial, Helvetica, sans-serif; color:#666}*/
#wrapper {width:100%;}
/*.form {float:left; padding:0 10px 10px 10px; background:#f3f3f3; border:2px solid #cfcfcf}
.form label {float:left; width:100px; padding:10px 10px 0 0; font-weight:bold}
.form select {float:left; width:146px; margin-top:10px}
.form input {float:left; margin-top:10px}
.form .submit {clear:both}*/
#msg {display:none; position:absolute; z-index:200; background:url(../images/msg_arrow.gif) left center no-repeat; padding-left:7px}
#msgcontent {display:block; background:#f3e6e6; border:2px solid #924949; border-left:none; padding:5px; min-width:150px; max-width:250px}

/**************************************************************/

/************************style.css*****************************/

body{font-family:Verdana, Arial, Helvetica, sans-serif;font-size:12px;}
table{ margin:0 auto; border:1px #999999 solid;}
th{ text-align:left;font-size:14px; background-color:#F7F7F7; height:35px;}
td{ text-align:left;}
span{color:#FF0000;}
div{text-align:right;}
.link{text-align:center; }

/**************************************************************/

/************************messages.js***************************/

// form validation function //
function validate(form) {
var name = form.name.value;
var email = form.email.value;
var pass = form.pass.value;
var repass = form.repass.value;


var NameRegex = /^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
var EmailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;

//var messageRegex = new RegExp(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim);

if(name == "") {
inlineMsg('name','You must enter name.',2);
return false;
}
if(!name.match(NameRegex)) {
inlineMsg('name','You have entered an invalid name.',2);
return false;
}
if(email == "") {
inlineMsg('email','Error
You must enter email.',2);
return false;
}
if(!email.match(EmailRegex)) {
inlineMsg('email','Error
You have entered an invalid email.',2);
return false;
}

if(pass==""){
inlineMsg('pass','Error
You must enter password.',2);
return false;
}
if(pass.length<6){>Error
Password should be more than 6 characters.',2);
return false;
}
if(pass!=repass){
inlineMsg('repass','Error
Password should be same.',2);
return false;
}

return true;
}


//Date Validation Code

function isValidDate(ctrl){

var dateStr = ctrl;
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null){
//alert("Invalid date format. Please enter the date in the MM/DD/YY format (example: 1/15/08) or select a date by clicking the calendar icon.")
//ctrl.focus();
return false;
}
month = matchArray[1]; // parse date into variables
day = matchArray[3];
year = matchArray[4];
if (month <> 12){
// check month range
//alert("Month must be between 1 and 12.");
return false;
}
if (day <> 31){
//alert("Day must be between 1 and 31.");
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31){
//alert("Month "+month+" doesn't have 31 days!")
return false
}
if (month == 2){
// check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
//alert("February " + year + " doesn't have " + day + " days!");
return false;
}
}
return true; // date is valid
}
//End Date Validation Code

///////// RED ALERT FOR BIGNNERS //////////////


// START OF MESSAGE SCRIPT //

var MSGTIMER = 20;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;

// build out the divs, set attributes and call the fade function //
function inlineMsg(target,string,autohide) {
var msg;
var msgcontent;
if(!document.getElementById('msg')) {
msg = document.createElement('div');
msg.id = 'msg';
msgcontent = document.createElement('div');
msgcontent.id = 'msgcontent';
document.body.appendChild(msg);
msg.appendChild(msgcontent);
msg.style.filter = 'alpha(opacity=0)';
msg.style.opacity = 0;
msg.alpha = 0;
} else {
msg = document.getElementById('msg');
msgcontent = document.getElementById('msgcontent');
}
msgcontent.innerHTML = string;
msg.style.display = 'block';
var msgheight = msg.offsetHeight;
var targetdiv = document.getElementById(target);
targetdiv.focus();
var targetheight = targetdiv.offsetHeight;
var targetwidth = targetdiv.offsetWidth;
var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
msg.style.top = topposition + 'px';
msg.style.left = leftposition + 'px';
clearInterval(msg.timer);
msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
if(!autohide) {
autohide = MSGHIDE;
}
window.setTimeout("hideMsg()", (autohide * 1000));
}

// hide the form alert //
function hideMsg(msg) {
var msg = document.getElementById('msg');
if(!msg.timer) {
msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
}
}

// face the message box //
function fadeMsg(flag) {
if(flag == null) {
flag = 1;
}
var msg = document.getElementById('msg');
var value;
if(flag == 1) {
value = msg.alpha + MSGSPEED;
} else {
value = msg.alpha - MSGSPEED;
}
msg.alpha = value;
msg.style.opacity = (value / 100);
msg.style.filter = 'alpha(opacity=' + value + ')';
if(value >= 99) {
clearInterval(msg.timer);
msg.timer = null;
} else if(value <= 1) {
msg.style.display = "none";
clearInterval(msg.timer);
}
}

// calculate the position of the element in relation to the left of the browser //
function leftPosition(target) {
var left = 0;
if(target.offsetParent) {
while(1) {
left += target.offsetLeft;
if(!target.offsetParent) {
break;
}
target = target.offsetParent;
}
} else if(target.x) {
left += target.x;
}
return left;
}

// calculate the position of the element in relation to the top of the browser window //
function topPosition(target) {
var top = 0;
if(target.offsetParent) {
while(1) {
top += target.offsetTop;
if(!target.offsetParent) {
break;
}
target = target.offsetParent;
}
} else if(target.y) {
top += target.y;
}
return top;
}

// preload the arrow //
if(document.images) {
arrow = new Image(7,80);
arrow.src = "images/msg_arrow.gif";
}


/**************************************************************/

/************************jsvalidationdemo.php******************/
Link below files into your html

href="css/style.css"
href="css/messages.css"
src="scripts/messages.js"

add this code into your form tag

form name="myform" onsubmit="return validate(this);"



/**************************************************************/




No comments:

Post a Comment