0

I am adding a data validation to my code. I want to make sure the event title is not blank, and the zip code entered is valid. The javascript does not work. Can you tell me why?

<form name="form1" action="organize.php" onSubmit="return validateform1();" method="post" enctype="multipart/form-data">            

    <div class="form-element">
        <label for="event_title">Event Title</label>
        <input type="text" name="event_title" id="dob" />
    </div>

    <div class="form-element">
        <label for="zip">Zip Code</label>
        <input type="text" name="zip" id="dob" />
    </div>

    <script language="javascript">

        function validateform1(){        

            var zipcode = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;        
            if(document.form1.event_title.value==""){
                alert("Enter a title");
                return false;
            }        
            else if((!document.form1.zip.value.match(zipcode)){  
                alert("wrong zip format");  
                return false;  
            }  
    </script>

</form>
8
  • What if they live in a country that doesn't have ZIP codes? Hope this is local-only? Commented Mar 5, 2014 at 9:45
  • what is the zip-code format u want to validate??? Commented Mar 5, 2014 at 9:46
  • @WayneWhitty yes for now! Commented Mar 5, 2014 at 9:48
  • @NoobEditor the format is either 5 digits or 5+4 digits: 99999 or 99999-9999 Commented Mar 5, 2014 at 9:49
  • 1
    Probably doesn't help that your ZIP field has id="dob". Anyway, what do you mean by "The javascript does not work."? What happens when it runs, do you get an error reported in the browser's console, or does something happen but the wrong thing, or...? Commented Mar 5, 2014 at 9:49

2 Answers 2

2

you have missed closing ) in this line:

else  if((!document.form1.zip.value.match(zipcode))  { 

should be :

else  if((!document.form1.zip.value.match(zipcode)))  { 

or:

else  if(!document.form1.zip.value.match(zipcode))  { 

Always you should see browser console.you can see hint to get rid of your issues.

Sign up to request clarification or add additional context in comments.

Comments

1

Probably doesn't help that your ZIP field has id="dob", but I think the main issue is that your function is missing a closing }, and your else if (( has an extra (. Try this:

function validateform1() {

    var zipcode = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
    if (document.form1.event_title.value == "") {
        alert("Enter a title");
        return false;
    } else if (!document.form1.zip.value.match(zipcode)) {
        alert("wrong zip format");
        return false;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.