Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

FORM VALIDATION| need help! | Cant add variable 1

Status
Not open for further replies.

passam

Programmer
Jan 20, 2009
1
US
FORM VALIDATION| need help! | Cant add variable

JavaScript that helps to validate my feedback form. This script has 4 variabels I think, name | email gender | message . I do not need gender var I would like to add a number var and validate it as well, for example I dont care about amount of numbers or area code, but I need to eliminate symbols line % & @ and so on.
After playing with it I get sytax errors and so on. I really dont know JavaScript and killed more than a day trying to complete it.
If anyone can help me thank you in advance!


Code:
// form validation function //
function validate(form) {
  var name = form.name.value;
  var email = form.email.value;
  var gender = form.gender.value;
  var message = form.message.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 your name.',2);
    return false;
  }
  if(!name.match(nameRegex)) {
    inlineMsg('name','You have entered an invalid name.',2);
    return false;
  }
  if(email == "") {
    inlineMsg('email','<strong>Error</strong><br />You must enter your email.',2);
    return false;
  }
  if(!email.match(emailRegex)) {
    inlineMsg('email','<strong>Error</strong><br />You have entered an invalid email.',2);
    return false;
  }
  if(gender == "") {
    inlineMsg('gender','<strong>Error</strong><br />You must select your gender.',2);
    return false;
  }
  if(message == "") {
    inlineMsg('message','You must enter a message.');
    return false;
  }
  if(message.match(messageRegex)) {
    inlineMsg('message','You have entered an invalid message.');
    return false;
  }
  return true;
}

// 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"; 
}


</script>

this is the form:

Code:
<form name="form" id="form" class="form" action="mypage.php" onsubmit="return validate(this)" method="post">
    <label for="name">Full Name:</label>
    <input type="text" name="name" id="name" />
    <label for="email">Email Address:</label>
    <input type="text" name="email" id="email" />
    <label for="gender">Gender:</label>
    <select name="gender" id="gender">
      <option value ="">Please Select</option>
      <option value ="male">Male</option>
      <option value ="female">Female</option>
    </select>
    <label for="message">Message:</label>
    <input type="text" name="message" id="message" />
    <input type="submit" value="Submit" class="submit" />
  </form>
 
Code:
<form name="form" id="form" class="form" action="mypage.php" onsubmit="return validate(this)" method="post">
    <label for="name">Full Name:</label>
    <input type="text" name="name" id="name" />
    <label for="email">Email Address:</label>
    <input type="text" name="email" id="email" />
    <label for="number">Phone Number:</label>
    <input type="text" name="number" id="number" />
    <label for="message">Message:</label>
    <input type="text" name="message" id="message" />
    <input type="submit" value="Submit" class="submit" />
  </form>

<script language="javascript">
	// form validation function //
function validate(form) {
  var name = form.name.value;
  var email = form.email.value;
  var number = form.number.value;
  var message = form.message.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);
  var numberRegex = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
  if(name == "") {
    inlineMsg('name','You must enter your name.',2);
    return false;
  }
  if(!name.match(nameRegex)) {
    inlineMsg('name','You have entered an invalid name.',2);
    return false;
  }
  if(email == "") {
    inlineMsg('email','<strong>Error</strong><br />You must enter your email.',2);
    return false;
  }
  if(!email.match(emailRegex)) {
    inlineMsg('email','<strong>Error</strong><br />You have entered an invalid email.',2);
    return false;
  }
  
  if(number == "") {
    inlineMsg('number','<strong>Error</strong><br />You must enter your number.',2);
    return false;
  }
  if(!number.match(numberRegex)) {
    inlineMsg('number','<strong>Error</strong><br />You have entered an invalid number.',2);
    return false;
  }

  if(message == "") {
    inlineMsg('message','You must enter a message.');
    return false;
  }
  if(message.match(messageRegex)) {
    inlineMsg('message','You have entered an invalid message.');
    return false;
  }
  return true;
}

// 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";
}


</script>
 
Kendel,

Nice work. I could see that what was needed was simply another regex for number and a check against it, but I don't speak regex and couldn't help the OP.

Although perhaps slightly off toppic of javascript, if you have a minute would you tell a regex illiterate what

var numberRegex = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;

does? How do you read this in English?

TIA.


 
Thank you TIA but I don't speak Regex either. I just wanted to help the OP so I google it. It's been a long time since I last used regex, I have to look up the index table in order to tell what each symbol/character does in English. I think it's complex because it allows users to enter other characters like spaces, hyphens, parentheses follows some rules.
There are some other simpler ones like:

numberRegex = /^\(\d\d\d\) \d\d\d-\d\d\d\d$/;
or
numberRegex = /^\(\d{3]\) \d{3}-\d{4}$/;

It’s up to the OP.
 
Hi

BigRed1212, there is nothing tricky :
Code:
/
^            [gray]// must start here[/gray]
(
  (
    \+       [gray]// string "+"[/gray]
    \d{1,3}  [gray]// digit character, at least 1, most 3 times[/gray]
    (-| )?   [gray]// string "-" or " ", 0 or 1 time[/gray]
    \(?      [gray]// string "(", 0 or 1 time[/gray]
    \d       [gray]// digit character[/gray]
    \)?      [gray]// string ")", 0 or 1 time[/gray]
    (-| )?   [gray]// string "-" or " ", 0 or 1 time[/gray]
    \d{1,5}  [gray]// digit character, at least 1, most 5 times[/gray]
  )
  |          [gray]// previous group or next group[/gray]
  (
    \(?      [gray]// string "(", 0 or 1 time[/gray]
    \d{2,6}  [gray]// digit character, at least 2, most 6 times[/gray]
    \)?      [gray]// string ")", 0 or 1 time[/gray]
  )
)
(-| )?       [gray]// string "-" or " ", 0 or 1 time[/gray]
(\d{3,4})    [gray]// digit character, at least 3, most 4 times[/gray]
(-| )?       [gray]// string "-" or " ", 0 or 1 time[/gray]
(\d{4})      [gray]// digit character, 4 times[/gray]
(
  ( x| ext)  [gray]// string " x" or " ext"[/gray]
  \d{1,5}    [gray]// digit character, at least 1, most 5 times[/gray]
){0,1}       [gray]// previous group 0 or 1 time[/gray]
$            [gray]// must end here[/gray]
/
Maybe it is just me, but when passam wrote "number", I thought to number, not phone number...

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top