-3

I'm coding a simple form with html w/javascript and have been working on this one aspect for about two days. I've seen numerous ideas across the internet but none seem to give me an idea of what to do. So hoping you guys can help.

Basically what has to happen is when USA is selected the form should require that a numeric postal code be entered or else it refuses submission. Below is my code so far, sorry its pretty lengthy.

        <label id="stateLabel" for="state">State</label>
        <select name="state" id="state" onchange="validateState()">
            <option value="">Select a State</option>
            <option value="AL">Alabama</option>
            <option value="AK">Alaska</option>
            <option value="AZ">Arizona</option>
            <option value="AR">Arkansas</option>
            <option value="CA">California</option>
            <option value="CO">Colorado</option>
            <option value="CT">Connecticut</option>
            <option value="DE">Delaware</option>
            <option value="DC">District Of Columbia</option>
            <option value="FL">Florida</option>
            <option value="GA">Georgia</option>
            <option value="HI">Hawaii</option>
            <option value="ID">Idaho</option>
            <option value="IL">Illinois</option>
            <option value="IN">Indiana</option>
            <option value="IA">Iowa</option>
            <option value="KS">Kansas</option>
            <option value="KY">Kentucky</option>
            <option value="LA">Louisiana</option>
            <option value="ME">Maine</option>
            <option value="MD">Maryland</option>
            <option value="MA">Massachusetts</option>
            <option value="MI">Michigan</option>
            <option value="MN">Minnesota</option>
            <option value="MS">Mississippi</option>
            <option value="MO">Missouri</option>
            <option value="MT">Montana</option>
            <option value="NE">Nebraska</option>
            <option value="NV">Nevada</option>
            <option value="NH">New Hampshire</option>
            <option value="NJ">New Jersey</option>
            <option value="NM">New Mexico</option>
            <option value="NY">New York</option>
            <option value="NC">North Carolina</option>
            <option value="ND">North Dakota</option>
            <option value="OH">Ohio</option>
            <option value="OK">Oklahoma</option>
            <option value="OR">Oregon</option>
            <option value="PA">Pennsylvania</option>
            <option value="RI">Rhode Island</option>
            <option value="SC">South Carolina</option>
            <option value="SD">South Dakota</option>
            <option value="TN">Tennessee</option>
            <option value="TX">Texas</option>
            <option value="UT">Utah</option>
            <option value="VT">Vermont</option>
            <option value="VA">Virginia</option>
            <option value="WA">Washington</option>
            <option value="WV">West Virginia</option>
            <option value="WI">Wisconsin</option>
            <option value="WY">Wyoming</option>
        </select>
        <div id="stateError" class="errorMessage"></div>
        <br />

        <label id="countryLabel" for="country">Country</label>
        <select name="country" id="country" onchange="validateCountry()">
            <option value="">Select a Country</option>
            <option value="US">United States of America</option>
            <option value="CAN">Canada</option>
            <option value="MEX">Mexico</option>
        </select>
        <div id="countryError" class="errorMessage"></div>
        <br />

        <label id="postCodeLabel" for="postCode">Postal Code</label>
        <input type="text" name="postCode" id="postCode" onblur="validatePostCode()" onfocus="resetPostCode()" />
        <div id="postCodeError" class="errorMessage"></div>
        <br />

Javascript

       var lStateLabel;
       var ddState;
       var dStateError;

       var lCountryLabel;
       var ddCountry;
       var dCountryError;

       var lPostCodeLabel;
       var iPostCode;
       var dPostCodeError;

       function validatePostCode()
       {
        if((isNaN(iPostCode.value) == false) && (iPostCode.value.length == 5))
       {
         resetPostCode();

          return true;
        }
       else
       {
        lPostCodeLabel.style.color = "red";
        dPostCodeError.innerHTML = "Your Postal Code must be numeric and 5 integers long.";

        return false;
        }
       }
Eric Smith
  • 11
  • 8
  • 6
    If you post this much code you haven't narrowed the problem sufficiently. –  Feb 06 '15 at 23:36
  • 1
    Please put only the code you're written that's relevant to this specific problem. Its really hard to parse the entire document for the right code. – Aweary Feb 06 '15 at 23:37
  • 1
    *"Basically what has to happen is when USA is selected the form should require that a numeric postal code..."* So much for [Zip+4](http://en.wikipedia.org/wiki/ZIP_code#ZIP.2B4), then. Only been around for 32 years, no rush to adopt it. – T.J. Crowder Feb 06 '15 at 23:41
  • You should set up regular expressions for the patterns you wish to validate against (e.g. `/^\d+$/` for digits only) and associate them with the country that requires that pattern. Then when the country is selected, grab the pattern and test the value. – RobG Feb 06 '15 at 23:46
  • It's not that I haven't narrowed the problem sufficiently. I posted all of the code thinking maybe someone would want to see it all. I now see my flaw, as far as Zip+4 your right that would be the norm but for now I'm not worried about that. – Eric Smith Feb 06 '15 at 23:47
  • I know using something like this will check if the PostalCode is formatted for the U.S. var objRegExp = /(^\d{5}$)|(^\d{5}-\d{4}$)/; ____But what I don't understand is how to tie this in with only the USA being selected in the drop down instead of using it for every country. – Eric Smith Feb 07 '15 at 00:02

2 Answers2

0

The ZIP code should only be required when USA is selected? Otherwise, you can use HTML validation constraints for input attributes like max, min, required, type or even pattern (for RegExp).

David
  • 130
  • 1
  • 1
  • 11
  • The Postal Code/Zip Code is required for every Country but when USA is selected it needs to require a 5 digit number as opposed to allowing letters and different strings in the field that would be the norm for different post codes from numerous countries. I thought about using HTML to complete this, but really need to figure how to get JavaScript to check it. – Eric Smith Feb 06 '15 at 23:57
0

Here, I think this is what you're looking for:

HTML:

<form name="myForm" action="assignment-js-form-success.html" onsubmit="return validateForm()" method="post">

    <label id="firstNameLabel" for="firstName">First Name</label>
    <input type="text" name="firstName" id="firstName" onblur="validateFirstName()" onfocus="resetFirstName()" />
    <div id="firstNameError" class="errorMessage"></div>
    <br />

    <label id="lastNameLabel" for="lastName">Last Name</label>
    <input type="text" name="lastName" id="lastName" onblur="validateLastName()" onfocus="resetLastName()" />
    <div id="lastNameError" class="errorMessage"></div>
    <br />

    <label id="addressLabel" for="address">Address</label>
    <input type="text" name="address" id="address" onblur="validateAddress()" onfocus="resetAddress()" />
    <div id="addressError" class="errorMessage"></div>
    <br />

    <label id="cityLabel" for="city">City</label>
    <input type="text" name="city" id="city" onblur="validateCity()" onfocus="resetCity()" />
    <div id="cityError" class="errorMessage"></div>
    <br />

    <label id="stateLabel" for="state">State</label>
    <select name="state" id="state" onchange="validateState()">
        <option value="">Select a State</option>
        <option value="AL">Alabama</option>
        <option value="AK">Alaska</option>
        <option value="AZ">Arizona</option>
        <option value="AR">Arkansas</option>
        <option value="CA">California</option>
        <option value="CO">Colorado</option>
        <option value="CT">Connecticut</option>
        <option value="DE">Delaware</option>
        <option value="DC">District Of Columbia</option>
        <option value="FL">Florida</option>
        <option value="GA">Georgia</option>
        <option value="HI">Hawaii</option>
        <option value="ID">Idaho</option>
        <option value="IL">Illinois</option>
        <option value="IN">Indiana</option>
        <option value="IA">Iowa</option>
        <option value="KS">Kansas</option>
        <option value="KY">Kentucky</option>
        <option value="LA">Louisiana</option>
        <option value="ME">Maine</option>
        <option value="MD">Maryland</option>
        <option value="MA">Massachusetts</option>
        <option value="MI">Michigan</option>
        <option value="MN">Minnesota</option>
        <option value="MS">Mississippi</option>
        <option value="MO">Missouri</option>
        <option value="MT">Montana</option>
        <option value="NE">Nebraska</option>
        <option value="NV">Nevada</option>
        <option value="NH">New Hampshire</option>
        <option value="NJ">New Jersey</option>
        <option value="NM">New Mexico</option>
        <option value="NY">New York</option>
        <option value="NC">North Carolina</option>
        <option value="ND">North Dakota</option>
        <option value="OH">Ohio</option>
        <option value="OK">Oklahoma</option>
        <option value="OR">Oregon</option>
        <option value="PA">Pennsylvania</option>
        <option value="RI">Rhode Island</option>
        <option value="SC">South Carolina</option>
        <option value="SD">South Dakota</option>
        <option value="TN">Tennessee</option>
        <option value="TX">Texas</option>
        <option value="UT">Utah</option>
        <option value="VT">Vermont</option>
        <option value="VA">Virginia</option>
        <option value="WA">Washington</option>
        <option value="WV">West Virginia</option>
        <option value="WI">Wisconsin</option>
        <option value="WY">Wyoming</option>
    </select>
    <div id="stateError" class="errorMessage"></div>
    <br />

    <label id="countryLabel" for="country">Country</label>
    <select name="country" id="country" onchange="validateCountry(); if (iPostCode.value !== '') validatePostCode();">
        <option value="">Select a Country</option>
        <option value="US">United States of America</option>
        <option value="CAN">Canada</option>
        <option value="MEX">Mexico</option>
    </select>
    <div id="countryError" class="errorMessage"></div>
    <br />

    <label id="postCodeLabel" for="postCode">Postal Code</label>
    <input type="text" name="postCode" id="postCode" onblur="validatePostCode()" onfocus="resetPostCode()" />
    <div id="postCodeError" class="errorMessage"></div>
    <br />

    <label id="emailLabel" for="email">Email Address</label>
    <input type="text" name="email" id="email" value="" onblur="validateEmail()" onfocus="resetEmail()" />
    <div id="emailError" class="errorMessage"></div>
    <br />

    <label id="passwordLabel" for="password">Password</label>
    <input type="text" name="password" id="password" onblur="validatePassword()" onfocus="resetPassword()" />
    <div id="passwordError" class="errorMessage"></div>
    <br />

    <label id="passwordConfirmLabel" for="passwordConfirm">Confirm Password</label>
    <input type="text" name="passwordConfirm" id="passwordConfirm" onblur="validatePasswordConfirm()" onfocus="resetPasswordConfirm()" />
    <div id="passwordConfirmError" class="errorMessage"></div>
    <br />

    <input type="submit" value="Submit" id="submitButton" value="Check"/>
</form>

<div id="errorMessage"></div>

JavaScript:

function initialization() {

    lFirstNameLabel = document.getElementById("firstNameLabel");
    iFirstName = document.getElementById("firstName");
    dFirstNameError = document.getElementById("firstNameError");

    lLastNameLabel = document.getElementById("lastNameLabel");
    iLastName = document.getElementById("lastName");
    dLastNameError = document.getElementById("lastNameError");

    lAddressLabel = document.getElementById("addressLabel");
    iAddress = document.getElementById("address");
    dAddressError = document.getElementById("addressError");

    lCityLabel = document.getElementById("cityLabel");
    iCity = document.getElementById("city");
    dCityError = document.getElementById("cityError");

    lStateLabel = document.getElementById("stateLabel");
    ddState = document.getElementById("state");
    dStateError = document.getElementById("stateError");

    lCountryLabel = document.getElementById("countryLabel");
    ddCountry = document.getElementById("country");
    dCountryError = document.getElementById("countryError");

    lPostCodeLabel = document.getElementById("postCodeLabel");
    iPostCode = document.getElementById("postCode");
    dPostCodeError = document.getElementById("postCodeError");

    lEmailLabel = document.getElementById("emailLabel");
    iEmail = document.getElementById("email");
    dEmailError = document.getElementById("emailError");

    lPasswordLabel = document.getElementById("passwordLabel");
    iPassword = document.getElementById("password");
    dPasswordError = document.getElementById("passwordError");

    lPasswordConfirmLabel = document.getElementById("passwordConfirmLabel");
    iPasswordConfirm = document.getElementById("passwordConfirm");
    dPasswordConfirmError = document.getElementById("passwordConfirmError");

} // end initialization()

window.validateForm = function() {

    noErrors = true;

    if (validateFirstName() == false) noErrors = false;
    if (validateLastName() == false) noErrors = false;
    if (validateAddress() == false) noErrors = false;
    if (validateCity() == false) noErrors = false;
    if (validateState() == false) noErrors = false;
    if (validateCountry() == false) noErrors = false;
    if (validatePostCode() == false) noErrors = false;
    if (validateEmail() == false) noErrors = false;
    if (validatePassword() == false) noErrors = false;
    if (validatePasswordConfirm() == false) noErrors = false;

    return noErrors;

}; // end validateForm()

window.validateFirstName = function() {
    if (iFirstName.value.length > 1) {
        resetFirstName();
        return true;
    } else {
        lFirstNameLabel.style.color = "red";
        dFirstNameError.innerHTML = "First Name should be more than one character";
        return false;
    } // end if
}; // end validateFirstName()

window.resetFirstName = function() {
    lFirstNameLabel.style.color = "black";
    dFirstNameError.innerHTML = "";
}; // end resetFirstName()

window.validateLastName = function() {
    if (iLastName.value.length > 1) {
        resetLastName();
        return true;
    } else {
        lLastNameLabel.style.color = "red";
        dLastNameError.innerHTML = "Last Name should be more than one character!";
        return false;
    } // end if
}; // end validateLastName()

window.resetLastName = function() {
    lLastNameLabel.style.color = "black";
    dLastNameError.innerHTML = "";
}; // end resetLastName()

window.validateAddress = function() {
    if (iAddress.value.length > 1) {
        resetAddress();
        return true;
    } else {
        lAddressLabel.style.color = "red";
        dAddressError.innerHTML = "Address must be greater than one character.";
        return false;
    } // end if
}; // end validateAddress()

window.resetAddress = function() {
    lAddressLabel.style.color = "black";
    dAddressError.innerHTML = "";
}; // end resetAddress()

window.validateCity = function() {
    if (iCity.value.length > 1) {
        resetCity();
        return true;
    } else {
        lCityLabel.style.color = "red";
        dCityError.innerHTML = "You must input a valid city name.";
        return false;
    } // end if
}; // end validateCity()

window.resetCity = function() {
    lCityLabel.style.color = "black";
    dCityError.innerHTML = "";
}; // end resetCity()

window.validateState = function() {
    if (ddState.selectedIndex > 0) {
        resetState();
        return true;
    } else {
        lStateLabel.style.color = "red";
        dStateError.innerHTML = "You must select a state!";
        return false;
    } // end if
}; // end validateState()

window.resetState = function() {
    lStateLabel.style.color = "black";
    dStateError.innerHTML = "";
}; // end resetState()

window.validateCountry = function() {
    if (ddCountry.selectedIndex > 0) {
        resetCountry();
        return true;
    } else {
        lCountryLabel.style.color = "red";
        dCountryError.innerHTML = "You must select a country!";
        return false;
    } // end if
}; // end validateCountry()

window.resetCountry = function() {
    lCountryLabel.style.color = "black";
    dCountryError.innerHTML = "";
}; // end resetCountry()

window.validatePostCode = function() {

    // get currently selected country
    var countrySelectElem = document.getElementById('country');
    var countryValue = countrySelectElem.options[countrySelectElem.selectedIndex].value;

    // if US, require 5-digit postal code
    if (countryValue === 'US') {
        if (isNaN(iPostCode.value) == false && iPostCode.value.length == 5) {
            resetPostCode();
            return true;
        } else {
            lPostCodeLabel.style.color = "red";
            dPostCodeError.innerHTML = "Your US Postal Code must be numeric and 5 integers long.";
            return false;
        } // end if
    } else {
        // require non-empty for other countries
        if (iPostCode.value !== '') {
            resetPostCode();
            return true;
        } else {
            lPostCodeLabel.style.color = "red";
            dPostCodeError.innerHTML = "Your Postal Code must be non-empty.";
            return false;
        } // end if
    } // end if

}; // end validatePostCode()

window.resetPostCode = function() {
    lPostCodeLabel.style.color = "black";
    dPostCodeError.innerHTML = "";
}; // end resetPostCode()

window.validateEmail = function() {
    var pattern = /^([a-zA-Z0-9_.-]+)@([a-zA-Z0-9+_.-]+)\.([a-zA-Z]+)$/;
    if (pattern.test(iEmail.value)) {
        resetEmail();
        return true;
    } else {
        lEmailLabel.style.color ="red";
        dEmailError.innerHTML = "Valid Email address is required!";
        return false;
    } // end if
}; // end validateEmail()

window.resetEmail = function() {
    lEmailLabel.style.color = "black";
    dEmailError.innerHTML = "";
}; // end resetEmail()

window.validatePassword = function() {
    if (iPassword.value.length >= 6) {
        resetPassword();
        return true;
    } else {
        lPasswordLabel.style.color = "red";
        dPasswordError.innerHTML = "Password should be at least 6 characters!";
        return false;
    } // end if
}; // end validatePassword()

window.resetPassword = function() {
    lPasswordLabel.style.color = "black";
    dPasswordError.innerHTML = "";
}; // end resetPassword()

window.validatePasswordConfirm = function() {
    if (iPasswordConfirm.value === iPassword.value) {
        resetPasswordConfirm();
        return true;
    } else {
        lPasswordConfirmLabel.style.color = "red";
        dPasswordConfirmError.innerHTML = "Passwords must match!";
        return false;
    } // end if
}; // end validatePasswordConfirm()

window.resetPasswordConfirm = function() {
    lPasswordConfirmLabel.style.color = "black";
    dPasswordConfirmError.innerHTML = "";
}; // end resetPasswordConfirm()

// actual onload code
initialization();

http://jsfiddle.net/gpyd956e/

The relevant code is this:

window.validatePostCode = function() {

    // get currently selected country
    var countrySelectElem = document.getElementById('country');
    var countryValue = countrySelectElem.options[countrySelectElem.selectedIndex].value;

    // if US, require 5-digit postal code
    if (countryValue === 'US') {
        if (isNaN(iPostCode.value) == false && iPostCode.value.length == 5) {
            resetPostCode();
            return true;
        } else {
            lPostCodeLabel.style.color = "red";
            dPostCodeError.innerHTML = "Your US Postal Code must be numeric and 5 integers long.";
            return false;
        } // end if
    } else {
        // require non-empty for other countries
        if (iPostCode.value !== '') {
            resetPostCode();
            return true;
        } else {
            lPostCodeLabel.style.color = "red";
            dPostCodeError.innerHTML = "Your Postal Code must be non-empty.";
            return false;
        } // end if
    } // end if

}; // end validatePostCode()

Because the validation of the postal code depends on the currently-selected country, you have to retrieve it in the validation function and then branch on it. After that, you can do exactly the validation you need for each country.

Also, in order to keep the postal code field error message up-to-date for country changes, I added this to the onchange handler for the country field:

if (iPostCode.value !== '') validatePostCode();

This dynamically re-validates the postal code field for changes to the country field, but only if the user has actually typed something into the postal code field (you wouldn't want a change to the country field to trigger a postal code error message if the user hasn't typed any postal code yet).

I also made various fixes for things like typos and inconsistent function naming and calling, and adapted the code to jsFiddle, which I believe runs the JavaScript in a synthesized window.onload callback, requiring some changes to ensure true globalness where necessary.

bgoldst
  • 34,190
  • 6
  • 38
  • 64