RSS

Simple Javascript Form Field Validation

This entry was posted on Aug 09 2007

Quick Regex form validation to check if a field contains numbers only...

JavaScript:
  1. function isNumeric(elem, msg){
  2. var alphaExp = /^<strong>[0-9]</strong>+$/;
  3. if(elem.value.match(alphaExp)){
  4. return true;
  5. }else{
  6. alert(msg);
  7. elem.focus();
  8. return false;
  9. }
  10. }


now letters only...

JavaScript:
  1. function isAlpha(elem, msg){
  2. var alphaExp = /^<strong>[a-zA-Z]</strong>+$/;
  3. if(elem.value.match(alphaExp)){
  4. return true;
  5. }else{
  6. alert(msg);
  7. elem.focus();
  8. return false;
  9. }
  10. }

now alphaNumeric...

JavaScript:
  1. function isAlphaNumeric(elem, msg){
  2. var alphaExp = /^<strong>[0-9a-zA-Z]</strong>+$/;
  3. if(elem.value.match(alphaExp)){
  4. return true;
  5. }else{
  6. alert(msg);
  7. elem.focus();
  8. return false;
  9. }
  10. }

now alphaNumeric with underscores...

JavaScript:
  1. function isNumeric(elem, msg){
  2. var alphaExp = /^<strong>[0-9a-zA-Z_]</strong>+$/;
  3. if(elem.value.match(alphaExp)){
  4. return true;
  5. }else{
  6. alert(msg);
  7. elem.focus();
  8. return false;
  9. }
  10. }

now with a highlight on the field in question...

JavaScript:
  1. function isAlphaNumeric(elem, msg){
  2. var alphaExp = /^[0-9a-zA-Z_]+$/;
  3. if(elem.value.match(alphaExp)){
  4. return true;
  5. }else{
  6. alert(msg);
  7. <strong>elem.style.backgroundColor='#ff0000';</strong>
  8. elem.focus();
  9. return false;
  10. }
  11. }

usage (place the following in your opening form tag):

JavaScript:
  1. onsubmit="return isAlphaNumeric(document.getElementById('the_field_in_question'), 'your message!')"

... and make sure the input field itself has an ID of 'the_field_in_question'

Enjoy.
Meshach

Uncategorized


One Response to “Simple Javascript Form Field Validation”

  1. hi, I found your cloud search script on iloveyoutube.com and I'm trying to implement it on my web site, but without sucsess. I have different database, but I think that shouldn't be a problem but I always get an mysql_fetch_array(): supplied argument is not a valid MySQL result resource error... can you help?


Post a Comment