Solved

Any suggestions for javascript validation allowing blank fields?

Posted on 2011-03-16
13
551 Views
Last Modified: 2012-08-13
Hey guys. I have a form I need to validate, I have basically built all the validation from code I learnt by browsing online. The problem I am having is that I have a huge function called validateForm and it is called on submission of my form. Certain things are tricky to accomplish doing this.

I have a url validation but I need to allow this to be empty as it is optional field, but I have value set to each field so that an example of what to enter in each field is there so I can stop the form being submitted when the example url is left in the field, but what I really want to happen is that if that is left there or it is blank then the value submitted is nothing to the databse.

Also I am having the same issue with the telephone field as this is also optional and has example data in as default value.

ANy suggestions on how to complete these two validations would be greatly appreciated!!!

Here is the validation code:

 //-----------The following code ensures the date of birth is only entered in the following format dd/mm/yyyy -----------------------------------------------------
				
			function checkName(nameField) {
				if (nameField.value == "") {
					alert("Please enter your full name!");
					nameField.focus();
					return false;
				}
				if (nameField.value.indexOf(" ") == 0) {
					alert("Please remove leading spaces from your name!");
					nameField.focus();
					return false;
				}
				if (nameField.value.lastIndexOf(" ") == (nameField.value.length-1)) {
					alert("Please remove trailing spaces from your name!");
					nameField.focus();
					return false;
				}
				if (nameField.value.indexOf(" ") == -1) {
					alert("You must enter your first name and lastname");
					nameField.focus();
					return false;
				}
				return true;
			}


			function validNum(sVal, limit) {
				var retValue = true;
				for(var i = 0; i < sVal.length; i++) {
					if (isNaN(parseInt(sVal.charAt(i))) == true) {
						return false;
					}
				}

				var intVal = parseInt(sVal);
				if ((intVal < 0) || (intVal > limit)) {
					retValue = false;
				}
				return retValue;
			}

			function checkDate(item) {
				if ((item.value.charAt(2) == "/") && (item.value.charAt(5) == "/") && (item.value.length == 10)) {
					var day = item.value.substring(0, 2);
					var month = item.value.substring(3, 5);
					var year = item.value.substring(6, 10);
					if (validNum(day, 31) == false) {
						alert("Incorrect date format!\nPlease enter a valid day");
						item.focus();
						return false;
					}
					if (validNum(month, 12) == false) {
						alert("Incorrect date format!\nPlease enter a valid month");
						item.focus();
						return false;
					}
					if (validNum(year, 3999) == false) {
						alert("Incorrect date format!\nPlease enter a sensible year!");
						item.focus();
						return false;
					}
					return true;
				}
				alert("Incorrect date format!\nEnter: dd/mm/yyyy");
				item.focus();
				return false;
			}


function checkForm(myForm) {
			
			if (checkDate(myForm.elements['dob']) == false) {
				return false;
			}
		}
		
	
 //-----------The following function is for form field validation on the join page-------------------------------------------------------
 
	function validateForm()	//The following test whether the Registration Form on the join us page is all valid
		{

		
		var x=document.forms["myForm"]["fname"].value	//Check that the first name field is not empty
		if (x==null || x=="" || x=="Name" )
		  {
		  alert("First name must be filled out");
		  return false;
		  }

		 if (/[\d]/.test(document.getElementById("fname").value)) //Check that there are only letters in the first name field
		  {
			alert("Name cannot contain numbers, please re-enter your name!");
			return false;
		  }
		  
		  
	  
		  var x=document.forms["myForm"]["sname"].value	//Check that the surname field is not empty
		if (x==null || x=="" || x=="Surname" )
		  {
		  alert("Surname must be filled out");
		  return false;
		  }
		  
		  if (/[\d]/.test(document.getElementById("sname").value)) 	//Check that there are only letters in the surname field
		  {
			alert("Surname cannot contain numbers, please re-enter your name!");
			return false;
		  }
	
	var x=document.forms["myForm"]["dob"].value	//Check that the first name field is not empty
		if (x=="" || x=="DD/MM/YYYY" )
		  {
		  alert("Date of Birth must be entered");
		  return false;
		  }
		
		var x=document.forms["myForm"]["email"].value	//Check that the email address is a avalid email address
		var atpos=x.indexOf("@");
		var dotpos=x.lastIndexOf(".");
			if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length || x=="emailaddress@domain.com")
				{
				  alert("Not a valid e-mail address");
				  return false;
				}
			
		
		 var theurl=document.myForm.url.value;	//Check that the URL field has a valid url address entered
		 var tomatch= /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/
		 if ((!tomatch.test(theurl) ) || theurl =="http://www.this-is-where-you-enter-your-url.com")
		 {
			 alert("URL invalid. Try again.");
			 return false; 
		 }	
		
	}

Open in new window


And here is my Form:

<form name="myForm" action="add_done.cfm" onsubmit="return validateForm(this);" method="post">
						<h1>Registration form</h1>
						<h2>Press the sign-up button after checking your details are correct </h2>
						<p></p>
						

						<label for="firstName"> First name
						<span class="small">Add your name</span>
						</label>
						<input name="fname" type="text" id="fname" value="Name" onfocus="value=''"/>

						<label for="surname"> Surname
						<span class="small">Add your surname</span>
						</label>
						<input name="sname" type="text" id="sname" value="Surname"  onfocus="value=''" />

						<label for="dob"> Date of Birth
						<span class="small">Add your DOB</span>
						</label>
						<input name="dob" type="text" id="dob" value="DD/MM/YYYY"  onfocus="value=''"  onchange="checkDate(this);"   />

						<label for="email"> Email
						<span class="small">Add a valid email address</span>
						</label>
						<input name="email" type="text" id="email"  value="emailaddress@domain.com"  onfocus="value=''"  />

						<label for="tel"> Tel
						<span class="small">Optional</span>
						</label>
						<input name="tel" type="text" id="tel"  value="00441234567890"  onfocus="value=''" />

						<label for="tel"> Homepage
						<span class="small">Optional</span>
						</label>
						<input name="url" type="text" id="url"  value="http://www.this-is-where-you-enter-your-url.com"  onfocus="value=''" />

						<button type="submit" name="Submit" value="Add Record">Sign-up</button>
						<div class="spacer"></div>

						</form>

Open in new window



Thank you!!
0
Comment
Question by:deucalion0
13 Comments
 
LVL 17

Expert Comment

by:shinuq
ID: 35147262
you can check the jquery validator plugin. which does all these  
0
 

Author Comment

by:deucalion0
ID: 35147447
Hi Shinug, unfortunately I cannot use jquery for the purpose of this exercise!

Thanks!!
0
 
LVL 10

Expert Comment

by:Hans Langer
ID: 35148552
maybe reading all INPUT elements and validating them depending their "validation" tag, like this:
function validateForm(form){
	var els = form.getElementsByTagName('input')
	for(var i=0;i<els.length;i++){
		if(els[i].validation){
			var re = new RegExp(els[i].validation)
			if(!re.exec(els[i].value)){
				alert(els[i].name + ' is not valid')
				return false
			}
		}
	}
}

Open in new window

<input name="fname" type="text" id="fname" value="Name" onfocus="value=''" validation="[A-Za-z]"/>

Open in new window


0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 35148760
Here
<script>
 //-----------The following code ensures the date of birth is only entered in the following format dd/mm/yyyy -----------------------------------------------------
        
      function checkName(nameField) {
        if (nameField.value == "") {
          alert("Please enter your full name!");
          nameField.focus();
          return false;
        }
        if (nameField.value.indexOf(" ") == 0) {
          alert("Please remove leading spaces from your name!");
          nameField.focus();
          return false;
        }
        if (nameField.value.lastIndexOf(" ") == (nameField.value.length-1)) {
          alert("Please remove trailing spaces from your name!");
          nameField.focus();
          return false;
        }
        if (nameField.value.indexOf(" ") == -1) {
          alert("You must enter your first name and lastname");
          nameField.focus();
          return false;
        }
        return true;
      }


      function validNum(sVal, limit) {
        var retValue = true;
        for(var i = 0; i < sVal.length; i++) {
          if (isNaN(parseInt(sVal.charAt(i))) == true) {
            return false;
          }
        }

        var intVal = parseInt(sVal);
        if ((intVal < 0) || (intVal > limit)) {
          retValue = false;
        }
        return retValue;
      }

      function checkDate(item) {
        if ((item.value.charAt(2) == "/") && (item.value.charAt(5) == "/") && (item.value.length == 10)) {
          var day = item.value.substring(0, 2);
          var month = item.value.substring(3, 5);
          var year = item.value.substring(6, 10);
          if (validNum(day, 31) == false) {
            alert("Incorrect date format!\nPlease enter a valid day");
            item.focus();
            return false;
          }
          if (validNum(month, 12) == false) {
            alert("Incorrect date format!\nPlease enter a valid month");
            item.focus();
            return false;
          }
          if (validNum(year, 3999) == false) {
            alert("Incorrect date format!\nPlease enter a sensible year!");
            item.focus();
            return false;
          }
          return true;
        }
        alert("Incorrect date format!\nEnter: dd/mm/yyyy");
        item.focus();
        return false;
      }


    
  
 //-----------The following function is for form field validation on the join page-------------------------------------------------------
 
  function validateForm(theForm)  //The following test whether the Registration Form on the join us page is all valid
    {

    
    var x=theForm["fname"].value  //Check that the first name field is not empty
    if (x==null || x=="" || x=="Name" )
      {
      alert("First name must be filled out");
      theForm["fname"].focus();
      return false;
      }

     if (/[\d]/.test(document.getElementById("fname").value)) //Check that there are only letters in the first name field
      {
      alert("Name cannot contain numbers, please re-enter your name!");
      return false;
      }
      
      
    
      var x=theForm["sname"].value  //Check that the surname field is not empty
    if (x==null || x=="" || x=="Surname" )
      {
      alert("Surname must be filled out");
      theForm["sname"].focus();
      return false;
      }
      
      if (/[\d]/.test(document.getElementById("sname").value))   //Check that there are only letters in the surname field
      {
      alert("Surname cannot contain numbers, please re-enter your name!");
      return false;
      }
  
    var x=theForm["dob"].value  //Check that the first name field is not empty
    if (x=="" || x=="DD/MM/YYYY" )
      {
      alert("Date of Birth must be entered");
      theForm["dob"].focus();
      return false;
      }
    if (!checkDate(theForm["dob"])) return false;
    
    var x=theForm["email"].value  //Check that the email address is a avalid email address
    var atpos=x.indexOf("@");
    var dotpos=x.lastIndexOf(".");
      if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length || x=="emailaddress@domain.com")
        {
          alert("Not a valid e-mail address");
          theForm["email"].focus();
          return false;
        }
      

     var theurl=theForm["url"].value;  //Check that the URL field has a valid url address entered
     if (theurl!="" && theurl!=theForm["url"].defaultValue) {
       var tomatch= /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/
       if (!theurl.match(tomatch)) {
         alert("URL invalid. Try again.");
         theForm["url"].focus();
         return false; 
       }
     }  
     var tel=theForm["tel"].value;  //Check that the tel field has a valid tel entered
     if (tel!="" && tel!=theForm["tel"].defaultValue) {
       var tomatch= /\d{10}/
       if (!tel.match(tomatch)) {
         alert("Telephone invalid. Try again.");
         theForm["tel"].focus();
         return false; 
       }
     }  
    return true;
  }
</script>  
<form name="myForm" action="add_done.cfm" onsubmit="return validateForm(this);" method="post">
<h1>Registration form</h1><h2>Press the sign-up button after checking your details are correct </h2>
  <p></p>
  <label for="firstName"> First name
    <span class="small">Add your name</span>
  </label>
  <input name="fname" type="text" id="fname" value="Name" 
    onfocus="value=''" onblur="if (this.value=='') this.value=this.defaultValue"/>
  <label for="surname"> Surname
    <span class="small">Add your surname</span>
  </label>
  <input name="sname" type="text" id="sname" value="Surname"  
    onfocus="value=''" onblur="if (this.value=='') this.value=this.defaultValue"/>
  <label for="dob"> Date of Birth
    <span class="small">Add your DOB</span>
  </label>
  <input name="dob" type="text" id="dob" value="DD/MM/YYYY"  
    onfocus="value=''" onblur="if (this.value=='') this.value=this.defaultValue" />
  <label for="email"> Email
    <span class="small">Add a valid email address</span>
  </label>
  <input name="email" type="text" id="email"  value="emailaddress@domain.com" 
    onfocus="value=''" onblur="if (this.value=='') this.value=this.defaultValue"/>
  <label for="tel"> Tel
    <span class="small">Optional</span>
  </label>
  <input name="tel" type="text" id="tel"  value="00441234567890"  
  onfocus="value=''" onblur="if (this.value=='') this.value=this.defaultValue"/>
  <label for="tel"> Homepage
    <span class="small">Optional</span>
  </label>
  <input name="url" type="text" id="url"  value="http://www.this-is-where-you-enter-your-url.com"  
  onfocus="this.value=''" onblur="if (this.value=='') this.value=this.defaultValue" />
  <button type="submit" name="Submit" value="Add Record">Sign-up
  </button>
  <div class="spacer">
  </div>
</form>

Open in new window

0
 

Author Comment

by:deucalion0
ID: 35149040
Hey guys thanks a lot for your help, it has been of lots of help!

mplungjan, I am trying your code now, but it still has the issue where I can submit the live form to the database when unchanging the default values of telephone and url, in the database the default values are submitted as the telephone and url. Is it possible to have it so that if the user does not change the set values in these two fields that nothing is sent to the database? I tried it a few times it just keeps submitting it all.

Thank, I feel like I am almost there, great code by the way!!!
0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 500 total points
ID: 35149109
Here. It will send empty value to the DB if the user does not touch the url/tel
<script>
 //-----------The following code ensures the date of birth is only entered in the following format dd/mm/yyyy -----------------------------------------------------
        
      function checkName(nameField) {
        if (nameField.value == "") {
          alert("Please enter your full name!");
          nameField.focus();
          return false;
        }
        if (nameField.value.indexOf(" ") == 0) {
          alert("Please remove leading spaces from your name!");
          nameField.focus();
          return false;
        }
        if (nameField.value.lastIndexOf(" ") == (nameField.value.length-1)) {
          alert("Please remove trailing spaces from your name!");
          nameField.focus();
          return false;
        }
        if (nameField.value.indexOf(" ") == -1) {
          alert("You must enter your first name and lastname");
          nameField.focus();
          return false;
        }
        return true;
      }


      function validNum(sVal, limit) {
        var retValue = true;
        for(var i = 0; i < sVal.length; i++) {
          if (isNaN(parseInt(sVal.charAt(i))) == true) {
            return false;
          }
        }

        var intVal = parseInt(sVal);
        if ((intVal < 0) || (intVal > limit)) {
          retValue = false;
        }
        return retValue;
      }

      function checkDate(item) {
        if ((item.value.charAt(2) == "/") && (item.value.charAt(5) == "/") && (item.value.length == 10)) {
          var day = item.value.substring(0, 2);
          var month = item.value.substring(3, 5);
          var year = item.value.substring(6, 10);
          if (validNum(day, 31) == false) {
            alert("Incorrect date format!\nPlease enter a valid day");
            item.focus();
            return false;
          }
          if (validNum(month, 12) == false) {
            alert("Incorrect date format!\nPlease enter a valid month");
            item.focus();
            return false;
          }
          if (validNum(year, 3999) == false) {
            alert("Incorrect date format!\nPlease enter a sensible year!");
            item.focus();
            return false;
          }
          return true;
        }
        alert("Incorrect date format!\nEnter: dd/mm/yyyy");
        item.focus();
        return false;
      }


    
  
 //-----------The following function is for form field validation on the join page-------------------------------------------------------
 
  function validateForm(theForm)  //The following test whether the Registration Form on the join us page is all valid
    {

    
    var x=theForm["fname"].value  //Check that the first name field is not empty
    if (x==null || x=="" || x=="Name" )
      {
      alert("First name must be filled out");
      theForm["fname"].focus();
      return false;
      }

     if (/[\d]/.test(document.getElementById("fname").value)) //Check that there are only letters in the first name field
      {
      alert("Name cannot contain numbers, please re-enter your name!");
      return false;
      }
      
      
    
      var x=theForm["sname"].value  //Check that the surname field is not empty
    if (x==null || x=="" || x=="Surname" )
      {
      alert("Surname must be filled out");
      theForm["sname"].focus();
      return false;
      }
      
      if (/[\d]/.test(document.getElementById("sname").value))   //Check that there are only letters in the surname field
      {
      alert("Surname cannot contain numbers, please re-enter your name!");
      return false;
      }
  
    var x=theForm["dob"].value  //Check that the first name field is not empty
    if (x=="" || x=="DD/MM/YYYY" )
      {
      alert("Date of Birth must be entered");
      theForm["dob"].focus();
      return false;
      }
    if (!checkDate(theForm["dob"])) return false;
    
    var x=theForm["email"].value  //Check that the email address is a avalid email address
    var atpos=x.indexOf("@");
    var dotpos=x.lastIndexOf(".");
      if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length || x=="emailaddress@domain.com")
        {
          alert("Not a valid e-mail address");
          theForm["email"].focus();
          return false;
        }
      

     var theurl=theForm["url"].value;  //Check that the URL field has a valid url address entered
     if (theurl!="" && theurl!=theForm["url"].defaultValue) {
       var tomatch= /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/
       if (!theurl.match(tomatch)) {
         alert("URL invalid. Try again.");
         theForm["url"].focus();
         return false; 
       }
     }  
     else theForm["url"].value="";
    
     var tel=theForm["tel"].value;  //Check that the URL field has a valid url address entered
     if (tel!="" && tel!=theForm["tel"].defaultValue) {
       var tomatch= /\d{10}/
       if (!tel.match(tomatch)) {
         alert("Telephone invalid. Try again.");
         theForm["tel"].focus();
         return false; 
       }
     }  
     else theForm["tel"].value="";
     
     return true; // allow submission
  }
</script>  
<form name="myForm" action="add_done.cfm" onsubmit="return validateForm(this);" method="post">
<h1>Registration form</h1><h2>Press the sign-up button after checking your details are correct </h2>
  <p></p>
  <label for="firstName"> First name
    <span class="small">Add your name</span>
  </label>
  <input name="fname" type="text" id="fname" value="Name" 
    onfocus="value=''" onblur="if (this.value=='') this.value=this.defaultValue"/>
  <label for="surname"> Surname
    <span class="small">Add your surname</span>
  </label>
  <input name="sname" type="text" id="sname" value="Surname"  
    onfocus="value=''" onblur="if (this.value=='') this.value=this.defaultValue"/>
  <label for="dob"> Date of Birth
    <span class="small">Add your DOB</span>
  </label>
  <input name="dob" type="text" id="dob" value="DD/MM/YYYY"  
    onfocus="value=''" onblur="if (this.value=='') this.value=this.defaultValue" />
  <label for="email"> Email
    <span class="small">Add a valid email address</span>
  </label>
  <input name="email" type="text" id="email"  value="emailaddress@domain.com" 
    onfocus="value=''" onblur="if (this.value=='') this.value=this.defaultValue"/>
  <label for="tel"> Tel
    <span class="small">Optional</span>
  </label>
  <input name="tel" type="text" id="tel"  value="00441234567890"  
  onfocus="value=''" onblur="if (this.value=='') this.value=this.defaultValue"/>
  <label for="tel"> Homepage
    <span class="small">Optional</span>
  </label>
  <input name="url" type="text" id="url"  value="http://www.this-is-where-you-enter-your-url.com"  
  onfocus="this.value=''" onblur="if (this.value=='') this.value=this.defaultValue" />
  <button type="submit" name="Submit" value="Add Record">Sign-up
  </button>
  <div class="spacer">
  </div>
</form>

Open in new window

0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:deucalion0
ID: 35149117
In fact the telephoneisnt checking validation either I can enter a single number or letter and it accpets this, or i can put in many letter, I am not sure why this is happening?

Thank you!
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 35149230
I did not add a great validation since I do not know what you will allow

var tomatch= /\d{10}/

is the regex and \d{10} means 10 digits.



Actually I also had a spelling mistake
change

       if (!test.match(tomatch))

to

       if (!tel.match(tomatch))

0
 

Author Comment

by:deucalion0
ID: 35149304
mplungjan, I owe you, that was great of you to help me with all that code, you really have helped me out! Solved!

I changed the telephone typo, that is now only accepting at least 10 characters so thanks, I'll try and figure out a way to have telephone validation for all countries ie 004412345678910 I dunno if its worth the hassle though!

But thanks a lot!!!

:)
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 35149350
0
 

Author Closing Comment

by:deucalion0
ID: 35149353
Excellent answer, very good code, and provided me with more than I asked for, but with code that I was needing and would have asked for help with anyway.

Thanks very much!
0
 

Author Comment

by:deucalion0
ID: 35149416
Hi Mplunigan, I had a look at the regular expression, I am needing to really study this as I have no idea which part starts or creates a match.

var tomatch= /\d{10}/

The first example which I am using oppossed to the second example which doesn't work, why does it not use this match but it uses the first one?

var tomatch= ^([\+][0-9]{1,3}([ \.\-])?)?([\(]{1}[0-9]{3}[\)])?([0-9A-Z \.\-]{1,32})((x|ext|extension)?[0-9]{1,4}?)$

I cannot determine a pattern as they both start and end differently.

Thank you!!
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 35149610
You need the / /
I.e /^....$/
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Today I would like to talk about localizing (Internationalization) JavaScript applications. Introduction When creating an application that is going to be used by many people around the globe, it is important to remember that not everyone speak…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now