SitePoint Sponsor

User Tag List

Results 1 to 8 of 8
  1. #1
    SitePoint Enthusiast
    Join Date
    Jan 2009
    Location
    Michigan
    Posts
    70
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    VERY simple form with Validation issues

    Hey guys, i'm just starting to learn javascript and know next to nothing about it.

    A friend of mine was helping me with validating a form and gave me the following script (which works like a charm) to make sure the user enters either a phone number or email address before submitting the form:

    Code:
    function checkPhoneEmail() {
    if ((document.getElementById('email').value=='' || document.getElementById('email').value==null) && (document.getElementById('phone').value=='' || document.getElementById('phone').value==null)) {
         alert("You must fill in a contact mehod: Phone or Email");
         return false;
      }
      else { return true; }
    }
    I also want to make sure the user provides a name on the form before submitting so i thought i might try to rework the code my friend did, but i can't get it going and really don't know where to start. I'm sure it's something simple, but being so new to all this, nothing seems simple haha.

    my code:
    Code:
    function checkName() {
    if (document.getElementById('name').value=='' || document.getElementById('name').value==null) {
    	alert("Please provide your name.");
    	return false;
    	}	
    	else {	return true; }
    }
    my Form:
    HTML Code:
    	<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" onsubmit="return checkPhoneEmail()">
    		<label>Name: <input type="text" name="name" id="name" /></label><br />
    		<label>Email: <input type="text" name="email" id="email"  /></label><br />
    		<label>Phone: <input type="text" name="phone" id="phone"></label><br>
    		<input type="submit" name="submit" value="Go!!" onSubmit="return checkName()" />
    	</form>
    Where'd did i go wrong?

    Thanks in advance for helping another newbie learn a bit!
    J
    Last edited by MainStWebGuy; Jun 4, 2009 at 08:48.

  2. #2
    SitePoint Guru
    Join Date
    Nov 2005
    Location
    Norway
    Posts
    715
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi, your code is missing a closing ) in the if statement.
    Code:
    function checkName() {
        if (document.getElementById('name').value=='' || document.getElementById('name').value==null)) {
    	alert("Please provide your name.");
    	return false;
        }	
        else { return true; }
    }

  3. #3
    SitePoint Enthusiast
    Join Date
    Jan 2009
    Location
    Michigan
    Posts
    70
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    hahahah man i fail.


    Thanks a lot!!!

  4. #4
    SitePoint Enthusiast
    Join Date
    Jan 2009
    Location
    Michigan
    Posts
    70
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    hrrmmm.... i've added that but still not working... does it really need the extra one? What is the second ")" closing?

  5. #5
    SitePoint Guru
    Join Date
    Nov 2005
    Location
    Norway
    Posts
    715
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ops my bad. I just quickly compared the two functions and noticed only one ) on the second one. But you're right, you only need one. To make it work I would do something like this instead:
    Code:
    <input type="submit" name="submit" value="Go!!" onclick="checkName()" />
    
    // or
    <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" onsubmit="checkName(); checkPhoneEmail();">
    
    // or better in a wrapper function
    function validate() {
        if (checkName() && checkPhoneEmail()) {
    	return true;
        }
    
        return false;
    }
    
    <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" onsubmit="validate()">

  6. #6
    SitePoint Enthusiast
    Join Date
    Jan 2009
    Location
    Michigan
    Posts
    70
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you much Fredda!!!

    i'll take what you have there and work it in :-)

    thanks again!
    J

  7. #7
    SitePoint Enthusiast
    Join Date
    Jan 2009
    Location
    Michigan
    Posts
    70
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ok i've taken the input from you guys (and a bit from my friend Google) and have reworked the script.

    It now successfully requires a name be given, it checks that a phone OR email is given, BUT it's requiring BOTH the phone and email when i'd like it to only require the phone OR email be given...

    Here's the code as it sits now (excluding the name checker):
    Code:
    //check to see that phone or email is filled in
    function checkPhoneEmail() {
    		
    	if ((document.form.VisitorEmail.value=="" || document.form.VisitorEmail.value==null) && (document.form.VisitorPhone.value=="" || document.form.VisitorPhone.value==null)) {
    		alert("You must fill in  Phone or Email");
    		return false;
    	}
    	return true;
    }
    
    //check for @ and . in the email address
    function echeck(str) {
    
    		var at="@"
    		var dot="."
    		var lat=str.indexOf(at)
    		var lstr=str.length
    		var ldot=str.indexOf(dot)
    		if (str.indexOf(at)==-1){
    		   alert("Invalid E-mail Address")
    		   return false
    		}
    
    		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
    		   alert("Invalid E-mail Address")
    		   return false
    		}
    
    		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
    		    alert("Invalid E-mail Address")
    		    return false
    		}
    
    		 if (str.indexOf(at,(lat+1))!=-1){
    		    alert("Invalid E-mail Address")
    		    return false
    		 }
    
    		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
    		    alert("Invalid E-mail Address")
    		    return false
    		 }
    
    		 if (str.indexOf(dot,(lat+2))==-1){
    		    alert("Invalid E-mail Address")
    		    return false
    		 }
    		
    		 if (str.indexOf(" ")!=-1){
    		    alert("Invalid E-mail Address")
    		    return false
    		 }
    
     		 return true					
    	}
    
    //validate email
    function ValidateEmail(){
    	var emailID=document.form.VisitorEmail
    	
    	if ((emailID.value==null)||(emailID.value=="")){
    		alert("Please Enter a Valid Email Address")
    		emailID.focus()
    		return false
    	}
    	if (echeck(emailID.value)==false){
    		emailID.value=""
    		emailID.focus()
    		return false
    	}
    	return true
     }
    
    //Phone Checker....
    
    var digits = "0123456789";
    var phoneNumberDelimiters = "()- ";
    // characters which are allowed in international phone numbers
    // (a leading + is OK)
    var validWorldPhoneChars = phoneNumberDelimiters + "+";
    // Minimum no of digits in an international phone no.
    var minDigitsInIPhoneNumber = 10;
    
    function isInteger(s)
    {   var i;
        for (i = 0; i < s.length; i++)
        {   
            // Check that current character is number.
            var c = s.charAt(i);
            if (((c < "0") || (c > "9"))) return false;
        }
        // All characters are numbers.
        return true;
    }
    function trim(s)
    {   var i;
        var returnString = "";
        // Search through string's characters one by one.
        // If character is not a whitespace, append to returnString.
        for (i = 0; i < s.length; i++)
        {   
            // Check that current character isn't whitespace.
            var c = s.charAt(i);
            if (c != " ") returnString += c;
        }
        return returnString;
    }
    function stripCharsInBag(s, bag)
    {   var i;
        var returnString = "";
        // Search through string's characters one by one.
        // If character is not in bag, append to returnString.
        for (i = 0; i < s.length; i++)
        {   
            // Check that current character isn't whitespace.
            var c = s.charAt(i);
            if (bag.indexOf(c) == -1) returnString += c;
        }
        return returnString;
    }
    
    function checkInternationalPhone(strPhone){
    var bracket=3
    strPhone=trim(strPhone)
    if(strPhone.indexOf("+")>1) return false
    if(strPhone.indexOf("-")!=-1)bracket=bracket+1
    if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
    var brchr=strPhone.indexOf("(")
    if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
    if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
    s=stripCharsInBag(strPhone,validWorldPhoneChars);
    return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
    }
    
    function ValidatePhone(){
    	var Phone=document.form.VisitorPhone
    	
    	if ((Phone.value==null)||(Phone.value=="")){
    		alert("Please Enter your Phone Number ex: 555-555-5555")
    		Phone.focus()
    		return false
    	}
    	if (checkInternationalPhone(Phone.value)==false){
    		alert("Please Enter a Valid Phone Number ex: 555-555-5555")
    		Phone.value=""
    		Phone.focus()
    		return false
    	}
    	return true
     }
    
    //check everything
    function CheckAll(){
    	if (checkName() &&	checkPhoneEmail() && ValidateEmail() && ValidatePhone()) {
    		return true;
    		}
    		else
    		{
    			return false;
    		}
    	
    }
    The form i am using calls the function CheckAll() like this:
    HTML Code:
    <form name="form" action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST" onSubmit="return CheckALL()">
    <!-- form fields -->
    </form>
    In my little world of scripting (which i am very new to) i would think that i would have to switch an "&&" to an "||" in the CheckAll() but when i tried that it didn't work out haha.

    Would it make sense to add to the ValidateEmail() something like...
    Code:
    if ((emailID.value==null)||(emailID.value=="") && (document.form.VisitorPhone.value !=null || document.form.VisitorPhone.value != "")){
    		alert("Please Enter a Valid Email Address")
    I sure do appreciate all the help you guys have given so far!
    Thanks Again all!
    J

  8. #8
    SitePoint Enthusiast
    Join Date
    Jan 2009
    Location
    Michigan
    Posts
    70
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It's all working! If anyone is interested, here's the complete code that will:

    1- Require a name be entered
    2- Require a phone or email be entered
    3- Ensure that the email and phone are in correct format

    I hope this can help someone out!

    Code:
    function checkName() {
    	if (document.form.VisitorName.value=="") {
    		alert("you must provide your name");
    		return false;
    	}
    	if (document.form.VisitorName.value.length < 2) {
    		alert("please enter your real name");
    		return false;
    	}
    	return true;
    }
    function checkPhoneEmail() {
    		
    	if ((document.form.VisitorEmail.value=="" || document.form.VisitorEmail.value==null) && 
    		 (document.form.VisitorPhone.value=="" || document.form.VisitorPhone.value==null)) {
    		alert("You must fill in  Phone or Email");
    		return false;
    	}
    	if ((document.form.VisitorEmail.value!="") && (document.form.VisitorEmail.value!=null)){
    			if (!ValidateEmail()){
    					return false;
    			}
    		}
    	if ((document.form.VisitorPhone.value!="") && (document.form.VisitorPhone.value!=null)){
    			if (!ValidatePhone()){
    				return false;
    			}
    		}
    	return true;
    }
    
    
    
    
    
    //		||---------Email Checker --------------||
    //check to make sure email has a @ and a . and that they are in legit places
    function echeck(str) {
    
    		var at="@"
    		var dot="."
    		var lat=str.indexOf(at)
    		var lstr=str.length
    		var ldot=str.indexOf(dot)
    		if (str.indexOf(at)==-1){
    		   alert("Invalid E-mail Address")
    		   return false
    		}
    
    		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
    		   alert("Invalid E-mail Address")
    		   return false
    		}
    
    		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
    		    alert("Invalid E-mail Address")
    		    return false
    		}
    
    		 if (str.indexOf(at,(lat+1))!=-1){
    		    alert("Invalid E-mail Address")
    		    return false
    		 }
    
    		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
    		    alert("Invalid E-mail Address")
    		    return false
    		 }
    
    		 if (str.indexOf(dot,(lat+2))==-1){
    		    alert("Invalid E-mail Address")
    		    return false
    		 }
    		
    		 if (str.indexOf(" ")!=-1){
    		    alert("Invalid E-mail Address")
    		    return false
    		 }
    
     		 return true					
    	}
    
    function ValidateEmail(){
    	var emailID=document.form.VisitorEmail
    	
    	if ((emailID.value==null)||(emailID.value=="")){
    		alert("Please Enter a Valid Email Address")
    		emailID.focus()
    		return false
    	}
    	if (echeck(emailID.value)==false){
    		emailID.value=""
    		emailID.focus()
    		return false
    	}
    	return true
     }
    
    
    
    
    
    
    //		||-----------Phone Checker -----------||
    // Declaring required variables
    var digits = "0123456789";
    // non-digit characters which are allowed in phone numbers
    var phoneNumberDelimiters = "()- ";
    // characters which are allowed in international phone numbers
    // (a leading + is OK)
    var validWorldPhoneChars = phoneNumberDelimiters + "+";
    // Minimum no of digits in an international phone no.
    var minDigitsInIPhoneNumber = 10;
    
    function isInteger(s)
    {   var i;
        for (i = 0; i < s.length; i++)
        {   
            // Check that current character is number.
            var c = s.charAt(i);
            if (((c < "0") || (c > "9"))) return false;
        }
        // All characters are numbers.
        return true;
    }
    function trim(s)
    {   var i;
        var returnString = "";
        // Search through string's characters one by one.
        // If character is not a whitespace, append to returnString.
        for (i = 0; i < s.length; i++)
        {   
            // Check that current character isn't whitespace.
            var c = s.charAt(i);
            if (c != " ") returnString += c;
        }
        return returnString;
    }
    function stripCharsInBag(s, bag)
    {   var i;
        var returnString = "";
        // Search through string's characters one by one.
        // If character is not in bag, append to returnString.
        for (i = 0; i < s.length; i++)
        {   
            // Check that current character isn't whitespace.
            var c = s.charAt(i);
            if (bag.indexOf(c) == -1) returnString += c;
        }
        return returnString;
    }
    
    function checkInternationalPhone(strPhone){
    var bracket=3
    strPhone=trim(strPhone)
    if(strPhone.indexOf("+")>1) return false
    if(strPhone.indexOf("-")!=-1)bracket=bracket+1
    if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
    var brchr=strPhone.indexOf("(")
    if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
    if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
    s=stripCharsInBag(strPhone,validWorldPhoneChars);
    return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
    }
    
    function ValidatePhone(){
    	var Phone=document.form.VisitorPhone
    	
    	if ((Phone.value==null)||(Phone.value=="")){
    		alert("Please Enter your Phone Number ex: 555-555-5555")
    		Phone.focus()
    		return false
    	}
    	if (checkInternationalPhone(Phone.value)==false){
    		alert("Please Enter a Valid Phone Number ex: 555-555-5555")
    		Phone.value=""
    		Phone.focus()
    		return false
    	}
    	return true
     }
    
    
    function CheckAll(){
    	if (checkName() &&	checkPhoneEmail()) {
    		return true;
    		}
    		else
    		{
    			return false;
    		}
    	
    }
    HTML Code:
    <form name="form" action="[PHP]<?php echo $_SERVER['PHP_SELF'];?>[/PHP]" method="POST" onSubmit="return CheckAll();">
    just make sure the name properties are "VisitorName", "VisitorEmail" and "VisitorPhone"

    Thanks again Fredda for helping on this!
    J


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •