如果在 JavaScript w/HTML 中选择了某个国家/地区,如何要求邮政编码为数字

How to require a Postal Code to be Numeric if a Certain Country is Selected in JavaScript w/HTML

我正在使用 html w/javascript 编写一个简单的表单,并且已经在这方面工作了大约两天。我在 Internet 上看到了很多想法,但 none 似乎让我知道该怎么做。所以希望大家帮忙。

基本上要发生的事情是选择美国时,表格应要求输入数字邮政编码,否则拒绝提交。下面是我目前的代码,抱歉太长了。

        <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;
        }
       }

只有在选择美国时才需要邮政编码吗?否则,您可以对输入属性使用 HTML 验证约束,例如 maxminrequiredtype 甚至 pattern(对于 RegExp) .

在这里,我想这就是你要找的:

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/

相关代码是这样的:

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()

因为邮政编码的验证取决于当前选择的国家,所以你必须在验证功能中检索它,然后在它上面分支​​。之后,您就可以针对每个国家/地区执行您需要的验证。

此外,为了使邮政编码字段错误消息在国家/地区更改时保持最新,我将其添加到国家/地区字段的 onchange 处理程序中:

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

这会动态重新验证邮政编码字段以更改国家/地区字段,但前提是用户确实在邮政编码字段中输入了某些内容(您不希望更改国家/地区字段来触发如果用户尚未输入任何邮政编码,则会出现邮政编码错误消息)。

我还对拼写错误和不一致的函数命名和调用等问题进行了各种修复,并将代码调整为 jsFiddle,我相信它在合成的 window.onload 回调中运行 JavaScript,需要一些必要时进行更改以确保真正的全球性。