Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 22
  1. #1
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Else statement being passed over and ignored?

    Hi, I'm having a very strange problem and for the life of me can't figure it out.

    I have a simple if else statement, the if part works correctly and if it passes it doesn't do the else.

    I use the exact same code for 2 other forms and it works, however for this one it completely ignores the word "else" All forms are done the same.

    Code:
    function validateCompanyInfoForm()
    {
    	if (!validateCompany() || !validateContact() || !validatePhoneNumber() || !validateEmail() || !validateWebsite())
    	{
    	   // do nothing
    	}
    	else
    	
    	document.forms["companyinformationform"].submit();
    	
    }
    I've tried wrapping the else statement, I've used
    Code:
    alert("test")
    under the else and it won't respond. If I put the alert under the if statement it prompts when it should.

    The id of my form is "companyinformationform" which I've done a copy and paste. I know its not the document clause because if doesn't matter what I put after the else it won't respond.

    Any ideas?

  • #2
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,302
    Thanks
    28
    Thanked 276 Times in 270 Posts
    Quote Originally Posted by robsworld78 View Post
    Any ideas?
    Your if condition could unexpectedly be returning true. Check that.

    Make sure that the form isn't submitting before the submit method is invoked (i.e., you've used event.preventDefault() to prevent premature form submission if this function is called when the form is submitted).

    Try adding brackets around your else statement. It's bad practice to omit them anyway for readability and troubleshooting reasons.

    I'd also use document.getElementById("companyinformationform") instead of document.forms["companyinformationform"]. There should be no change in functionality, but the former unambiguously refers to an element by ID whereas the latter can match a name attribute value.
    For every complex problem, there is an answer that is clear, simple, and wrong.

  • #3
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    O I'm having loads of fun here, luckily I have no hair to pull out.

    The if statement is good and when I add the alert to it, it only prompts when the if fails and when the if passes it doesn't prompt, as it should.

    Not sure about your 2nd suggestion, the form isn't submitting period. The button to submit is outside the form tags so it has to be submitted via javascript?

    I added the brackets and will continue to do that and have changed the tag you suggested however none of it made a difference.

    I have a bunch of forms and I'm just adding validation to them all. All forms are built the same and use the same form of validation. The first 2 forms worked as they should, this form is acting funny with the javascript function.

    I went on to my 4th form and used the same javascript function I posted and it works as it should, yes I know that says the function is good and the form is bad but the form is so simple and everything was copy and paste so no typos. The thing that tells me its not the form is I can't even get an alert to show up after the else statement, where as in the other 3 functions I can add that alert and it will show up, or it will submit the form if I tell it to do that. Only this function won't. Its very strange. Its like you suggested the if statement is always failing so it won't move on, but using the alert tag shows me that it does pass if everything is entered as it should be on the form.

    Is there a way to keep the submit buttons inside the form tag yet not submit until the javascript function passes.

    I moved the submit buttons outside the form tags because it was checking for validation but also submitting the form regardless.

    Then I moved the buttons used that document.form to submit the form and here I am.

  • #4
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Code:
    function validateRegisterForm()
    {
    	if (!validateUsername() || !validatePassword() || !validateCompany() || !validateContact() || !validateFromSuite() || !validateFromAddress() || !validateFromPostalCode() || !validatePhoneNumber() || !validateEmail() || !validateWebsite())
    	{
    	   // do nothing
    	}
    	else
    	{
    		alert("hello");
    		document.getElementById("accountregisterform").submit();
    	}
    }
    
    function validateCompanyInfoForm()
    {
    	if (!validateCompany() || !validateContact() || !validatePhoneNumber() || !validateEmail() || !validateWebsite())
    	{
    	   // do nothing
    	}
    	else	
    	{
    		alert("hello");
    		document.getElementById("companyinformationform").submit();	
    	}	
    }
    The top function shows alert and processes form.

    The bottom function won't alert or process form.

    Both function uses the same functions within the javascript file.

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,960
    Thanks
    79
    Thanked 4,424 Times in 4,389 Posts
    I think you are making a huge mistake, calling submit() like that.

    Instead, just do this:
    Code:
    <form id="companyInfoForm" ...>
    ...
    </form>
    <script type="text/javascript">
    document.getElementById("companyInforForm").onsubmit = 
        function( )
        {
    	return validateCompany() && validateContact() && validatePhoneNumber() 
                   && validateEmail()  && validateWebsite();
        }
        function validateCompany( ) ... etc. ...
    </script>
    </body>
    </html>
    Note that the JS code goes JUST BEFORE the </body> tag.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,960
    Thanks
    79
    Thanked 4,424 Times in 4,389 Posts
    But if you really have two <form>s on your page, then you may well have other major problems.

    I think you need to show us your actual HTML. Never mind the JavaScript.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Why would calling the forms that way be a huge mistake? If its not hard to explain I'm curious.

    As you can probably tell I'm just learning, this is the first web app I've made and its actually coming along nice, just a little slow, lol.

    Would calling the forms the way you suggested allow me to leave the submit buttons inside the form?

    Ultimately I would like to do that as I ran into other problems earlier with the button outside the tags.

    Would I just leave the form built as normal and add the script?

    I won't post the html just yet, I'll see what I can do here. Thanks for the help guys.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,960
    Thanks
    79
    Thanked 4,424 Times in 4,389 Posts
    Because two forms can't share a single form field.

    And yet you are doing (example) validateCompany() without (apparently) designating which form the field Company belongs to.

    So even if your code worked, if the field Company is in one <form> and not the other, then when the form without it is submitted the value of Company will *NOT* be sent to wherever the <form> posts to.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,960
    Thanks
    79
    Thanked 4,424 Times in 4,389 Posts
    You could perhaps clarify things by posting your code for validateCompany( ).

    But honest, the easiest way for us to help you is to see the entire web page.

    The easiest way to do that is to give us a live URL to the page, if possible.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #10
    Senior Coder Logic Ali's Avatar
    Join Date
    Sep 2010
    Location
    London
    Posts
    1,028
    Thanks
    0
    Thanked 207 Times in 202 Posts
    If you must do things this way, what happens if you do this?:

    Code:
    function validateCompanyInfoForm()
    {
       if (!validateCompany() || !validateContact() || !validatePhoneNumber() || !validateEmail() || !validateWebsite())
       {
         alert( "Invalid" );
       }
       else
       {
          alert( "OK Sending" );
          
          try
          {  
             document.forms["companyinformationform"].submit();
          }
          catch( e )
          {
            alert( 'Form addressing error' );
          }            
       }   
    }

  • #11
    Senior Coder Arbitrator's Avatar
    Join Date
    Mar 2006
    Location
    Splendora, Texas, United States of America
    Posts
    3,302
    Thanks
    28
    Thanked 276 Times in 270 Posts
    Quote Originally Posted by robsworld78 View Post
    Is there a way to keep the submit buttons inside the form tag yet not submit until the javascript function passes.
    All form controls, including submission buttons, should be within a form element unless you have no intention of submitting the form to a server, in which case you can simply omit the form element altogether.

    When you click something on a page and something happens without scripted intervention, that's called a "default action". Clicking a submission button within a form has a default action: it submits the form. To cancel the default action, use the preventDefault method on the event object associated with the default action. For example:

    Code:
    var submission_button = document.getElementById("submission_button");
    function validate_form(event) {
    	// An event argument is automatically passed by an event listener if you use a function as a direct event handler.
    	event.preventDefault();
    	// Form validation code goes here.
    }
    submission_button.addEventListener("click", validate_form);
    For every complex problem, there is an answer that is clear, simple, and wrong.

  • #12
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,068
    Thanks
    0
    Thanked 256 Times in 252 Posts
    If you have multiple forms with the same set of fields and are using those validation methods, then those methods must accept the form reference as parameter so that those methods would know which form to work on.

    Code:
    document.getElementById("companyInforForm").onsubmit = function(e) {
        return validateCompany(this) && validateContact(this) && validatePhoneNumber(this) && validateEmail(this)  && validateWebsite(this);
    }
    document.getElementById("otherFormHere").onsubmit = function(e) {
        return validateCompany(this) && validateContact(this) && validatePhoneNumber(this) && validateEmail(this)  && validateWebsite(this);
    }
    function validateCompany(objForm) {
         //validate inputs using objForm.fieldName.value, for example:
         if (objForm.xxxxxx.value == '') {
              return false;
         }
         //other validations here
    
        //return true at the end
         return true;
    }
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • #13
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    Thanks for all the input from everyone, very helpful.

    I ended up rebuilding the form that was causing problems as I wanted changes anyways, after rebuilding it worked like the others.

    Now I'm going to convert the forms back to the original method as in putting the submit buttons back inside the form tags.

    Here's what my client side validation code looks like, I'm going to put in some basic server side as well but I think in the end I'm going to try and add some code so if you don't have javascript enabled you can't use the site. It'll make my life a heck of a lot easier.

    Code:
    function validateUsername()
    {
    	var username = document.getElementById("username").value;
    	
    	if(username.length == 0)
    	{
    		producePrompt("Username is Required", "usernameprompt", "red");
    		return false;
    	}
    	if(username.length < 6)
    	{
    		producePrompt("Username is to short", "usernameprompt", "red");
    		return false;	
    	}
    	if(username.length > 20)
    	{
    		producePrompt("Username is to long", "usernameprompt", "red");
    		return false;	
    	}
    	if(!username.match(/^[A-za-z0-9\-]{6,20}$/))
    	{
    		producePrompt("Invalid Character", "usernameprompt", "red");
    		return false;	
    	}
    	
    	producePrompt("Username is Valid", "usernameprompt", "green");	
    	return true;		
    }
    
    function validatePassword()
    {
    	var password = document.getElementById("password").value;
    	
    	if(password.length == 0)
    	{
    		producePrompt("Password is Required", "passwordprompt", "red");
    		return false;
    	}
    	if(password.length < 6)
    	{
    		producePrompt("Password is to short", "passwordprompt", "red");
    		return false;	
    	}
    	if(password.length > 20)
    	{
    		producePrompt("Password is to long", "passwordprompt", "red");
    		return false;	
    	}
    	if(!password.match(/^\S{6,20}$/))
    	{
    		producePrompt("No Spaces Allowed", "passwordprompt", "red");
    		return false;	
    	}
    	
    	producePrompt("Password is Valid", "passwordprompt", "green");	
    	return true;		
    }
    
    function validateCompany()
    {
    	var company = document.getElementById("company").value;
    	
    	if(company.length == 0)
    	{
    		producePrompt("Company Name is Required", "companyprompt", "red");
    		return false;
    	}
    	if(company.length < 3)
    	{
    		producePrompt("3-45 Characters Allowed", "companyprompt", "red");
    		return false;	
    	}
    	if(company.length > 45)
    	{
    		producePrompt("3-45 Characters Allowed", "companyprompt", "red");
    		return false;	
    	}
    	if(!company.match(/^[\d,\w,\s#&@.",'\\()<>+\-|^!$/]{3,45}$/))
    	{
    		producePrompt("Invalid Character", "companyprompt", "red");
    		return false;	
    	}
    	
    	producePrompt("", "companyprompt", "green")
    	return true;
    }
    
    function validateContact()
    {
    	var contact = document.getElementById("contact").value;
    	
    	if(contact.length == 0)
    	{
    		producePrompt("Contact Name is Required", "contactprompt", "red");
    		return false;
    	}
    	if(contact.length < 3)
    	{
    		producePrompt("3-45 Characters Allowed", "contactprompt", "red");
    		return false;	
    	}
    	if(contact.length > 45)
    	{
    		producePrompt("3-45 Characters Allowed", "contactprompt", "red");
    		return false;	
    	}
    	if(!contact.match(/^[A-Za-z]*\s{1}[A-Za-z]{1}[A-Za-z]*$/))
    	{
    		producePrompt("First and Last Name Required", "contactprompt", "red");
    		return false;	
    	}
    	
    	producePrompt("", "contactprompt", "green");	
    	return true;
    }
    
    function validateFromSuite()
    {
    	var fromsuite = document.getElementById("fromsuite").value;
    	
    	if(fromsuite.length == 0)
    	{
    		producePrompt("", "fromsuiteprompt", "red");
    		return true;
    	}
    	if(fromsuite.length < 1)
    	{
    		producePrompt("1-10 Characters Allowed", "fromsuiteprompt", "red");
    		return false;	
    	}
    	if(fromsuite.length > 10)
    	{
    		producePrompt("1-10 Characters Allowed", "fromsuiteprompt", "red");
    		return false;	
    	}
    	if(!fromsuite.match(/^[\d,\w,\s&+\-/]{1,10}$/))
    	{
    		producePrompt("Invalid Character", "fromsuiteprompt", "red");
    		return false;	
    	}
    	
    	producePrompt("", "fromsuiteprompt", "green");	
    	return true;
    }
    
    function validateFromAddress()
    {
    	var fromaddress = document.getElementById("fromaddress").value;
    	
    	if(fromaddress.length == 0)
    	{
    		producePrompt("Address is Required", "fromaddressprompt", "red");
    		return false;
    	}
    	if(fromaddress.length < 3)
    	{
    		producePrompt("3-45 Characters Allowed", "fromaddressprompt", "red");
    		return false;	
    	}
    	if(fromaddress.length > 45)
    	{
    		producePrompt("3-45 Characters Allowed", "fromaddressprompt", "red");
    		return false;	
    	}
    	if(!fromaddress.match(/^[\d,\w,\s#&@.",'\\()<>+\-|^!$/]{3,45}$/))
    	{
    		producePrompt("Invalid Character", "fromaddressprompt", "red");
    		return false;	
    	}
    	
    	producePrompt("", "fromaddressprompt", "green");	
    	return true;
    }
    
    function validateFromPostalCode()
    {
    	var frompostalcode = document.getElementById("frompostalcode").value;
    	
    	if(frompostalcode.length == 0)
    	{
    		producePrompt("Postal Code is Required", "frompostalcodeprompt", "red");
    		return false;
    	}
    	
    	producePrompt("", "frompostalcodeprompt", "green");	
    	return true;
    }
    
    function validatePhoneNumber()
    {
    	var phonenumber = document.getElementById("phonenumber").value;
    	
    	if(phonenumber.length == 0)
    	{
    		producePrompt("Phone Number is Required", "phonenumberprompt", "red");
    		return false;
    	}
    	
    	producePrompt("", "phonenumberprompt", "green");	
    	return true;
    }
    
    function validateEmail()
    {
    	var email = document.getElementById("email").value;
    	
    	if(email.length == 0)
    	{
    		producePrompt("Email Address is Required", "emailprompt", "red");
    		return false;
    	}
    	if(email.length < 5)
    	{
    		producePrompt("5-45 Characters Allowed", "emailprompt", "red");
    		return false;	
    	}
    	if(email.length > 45)
    	{
    		producePrompt("5-45 Characters Allowed", "emailprompt", "red");
    		return false;	
    	}
    	if(!email.match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/))
    	{
    		producePrompt("Invalid Email Address", "emailprompt", "red");
    		return false;	
    	}
    	
    	producePrompt("", "emailprompt", "green");	
    	return true;
    }
    
    function validateWebsite()
    {
    	var website = document.getElementById("website").value;
    	
    	if(website.length == 0)
    	{
    		producePrompt("", "websiteprompt", "red");
    		return true;
    	}
    	if(website.length < 5)
    	{
    		producePrompt("5-45 Characters Allowed", "websiteprompt", "red");
    		return false;	
    	}
    	if(website.length > 45)
    	{
    		producePrompt("5-45 Characters Allowed", "websiteprompt", "red");
    		return false;	
    	}
    	if(website.match(/^[\w\d]*[.]{1}[\w]{2,6}$/))
    	{
    		producePrompt("Please include \"www.\"", "websiteprompt", "red");
    		return false;	
    	}
    	if(!website.match(/^[w]{3}[.]{1}[\w\d]*[.]{1}[\w]{2,6}$/))
    	{
    		producePrompt("Invalid Website Address", "websiteprompt", "red");
    		return false;	
    	}
    	
    	producePrompt("", "websiteprompt", "green")
    	return true;
    }
    
    
    
    
    
    
    function validateRegisterForm()
    {
    	if (!validateUsername() || !validatePassword() || !validateCompany() || !validateContact() || !validateFromSuite() || !validateFromAddress() || !validateFromPostalCode() || !validatePhoneNumber() || !validateEmail() || !validateWebsite())
    	{
    	   // do nothing
    	}
    	else
    	{
    		document.getElementById("accountregisterform").submit();
    	}
    }
    
    function validateCompanyInfoForm()
    {
    	if (!validateCompany() || !validateContact() || !validatePhoneNumber() || !validateWebsite() || !validateEmail())
    	{
    		if(validateCompany() == false)
    			{
    				alert("Please add a valid company name!");
    			}
    	   
    		if(validateContact() == false)
    			{
    				alert("Please add a valid contact name!");
    			}
    			
    		if(validatePhoneNumber() == false)
    			{
    				alert("Please add a valid phone number!");
    			}
    						
    		if(validateEmail() == false)
    			{
    				alert("Please add an valid email address!");
    			}			
    	}
    	else	
    	{
    	//	document.getElementById("companyinformationform").submit();	
    	SubmitCompanyInfoUpdate()
    	}	
    }
    
    function producePrompt(message, promptLocation, color)
    {
    	document.getElementById(promptLocation).innerHTML = message;
    	document.getElementById(promptLocation).style.color = color;	
    }
    The last function works with all the other functions and the 2nd and 3rd last functions are for validating before submitting.

    I'm able to reuse any of the functions for any form if they have that same field I just have to create a function for the submit button of each form.

    I don't have the website hosted yet, its just on my local machine so I can't post a link.

    Is this a good form of validation? Is this a good practice to follow for other sites?

  • #14
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    I call each of those functions on the form input field using the "onkeyup" event. It validates as you type in each field or when you hit submit.

  • #15
    New Coder
    Join Date
    Aug 2013
    Posts
    36
    Thanks
    6
    Thanked 0 Times in 0 Posts
    I found this method online, it seems like a good method because say for instance I have the field "username" on many forms. All I need to do for each form field is

    Code:
    <input id="username" onKeyUp="validateUsername()" name="ruser" type="text" style="width:200px; border: solid thin #888"/>


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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