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

Posted

技术标签:

【中文标题】如果在 JavaScript w/HTML 中选择了某个国家/地区,如何要求邮政编码为数字【英文标题】:How to require a Postal Code to be Numeric if a Certain Country is Selected in JavaScript w/HTML 【发布时间】:2015-02-06 23:34:18 【问题描述】:

我正在使用带有 javascripthtml 编写一个简单的表单,并且已经在这方面工作了大约两天。我在互联网上看到了很多想法,但似乎没有一个让我知道该怎么做。所以希望大家能帮忙。

基本上必须发生的是,选择USA时,表格应该要求输入数字邮政编码,否则它拒绝提交。以下是我到目前为止的代码,抱歉,它很长。

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

【问题讨论】:

如果您发布这么多代码,您还没有充分缩小问题范围。 请仅输入您编写的与此特定问题相关的代码。为正确的代码解析整个文档真的很难。 “基本上要发生的是什么时候选择美国的表单应该要求数字邮政编码...” i>为Zip+4,那么。才存在 32 年,不急于采用。 您应该为要验证的模式设置正则表达式(例如,/^\d+$/ 仅用于数字)并将它们与需要该模式的国家/地区相关联。然后当国家被选中时,抓取模式并测试值。 并不是我没有充分缩小问题的范围。我发布了所有的代码,想也许有人会想看到这一切。我现在看到了我的缺陷,就 Zip+4 你的权利而言,这将是常态,但现在我并不担心。 【参考方案1】:

在这里,我认为这就是您要寻找的:

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,需要进行一些更改以确保在必要时实现真正的全局性。

【讨论】:

太棒了,你给出的解释让它更清楚了。感谢您的帮助。【参考方案2】:

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

【讨论】:

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来自多个国家的邮政编码。我想过用 HTML 来完成这个,但真的需要弄清楚如何让 JavaScript 来检查它。

以上是关于如果在 JavaScript w/HTML 中选择了某个国家/地区,如何要求邮政编码为数字的主要内容,如果未能解决你的问题,请参考以下文章

如果选择了特定的付款方式,Woocommerce 仅运行 javascript

为啥在 JavaScript 中使用 getRangeAt() 会从选择中删除一些内容?

如何在javascript测验中为正确的选择和错误的选择着色?

JavaScript选择排序

使用 ajax/Javascript 动态验证用户选择

JavaScript图像裁剪/矩形选择图像