简体   繁体   English

如何使用JavaScript在此表单上验证邮政编码?

[英]How do I validate a Postcode on this form using JavaScript?

I'm not that experienced with JavaScript and I've been trying for a while now to make this form display an alert message if a postcode is entered in the wrong format when the user clicks the submit button. 我对JavaScript的了解还不是很丰富,现在我已经尝试了一段时间,如果用户单击“提交”按钮时以错误的格式输入了邮政编码,则此表单将显示一条警报消息。 What I've achieved so far I've placed all inside one function which validates all of the fields, I'm using names to make reference to the fields from inside the function. 到目前为止,我已经完成了什么工作,我都将所有内容放置在一个可以验证所有字段的函数中,我使用名称来引用函数内部的字段。 (Sorry if I haven't indented properly) (对不起,如果我没有正确缩进)

var g=document.forms["myform"]["postcode"].value;
if (g==null || g=="")
{
    alert("Please enter your Post CODE");
    return false;
}
var regPostcode = /^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9]
[a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}$/;
if(regPostcode.test(postcode) == false)
{
    alert("That Post Code is incorrect");
    return false;
}

Here's the HTML for the particular field inside the form im using 这是im使用的表单中特定字段的HTML

<div class=”field_container”><label>Post Code</label><input type=”text” name="postcode" id="postcode" /></div>

Also, you should add a simple accessibility enhancement like so: 另外,您应该添加一个简单的可访问性增强功能,如下所示:

<div class="field_container">
    <label for="postcode">Post Code</label> <!-- the "for" attribute should match the "id" attribute of the input it corresponds to -->
    <input type="text" name="postcode" id="postcode" />
</div>

Supposing that your regex is correct for the country you are aiming, I'd try something like this : 假设您的正则表达式对您要定位的国家/地区来说是正确的,我将尝试执行以下操作:

var g = document.forms["myform"]["postcode"].value;
var regPostcode = /^([a-zA-Z]){1}([0-9][0-9]|[0-9]|[a-zA-Z][0-9]
    [a-zA-Z]|[a-zA-Z][0-9][0-9]|[a-zA-Z][0-9]){1}([ ])([0-9][a-zA-z][a-zA-z]){1}$/;
if (!g)
{
    alert("Please enter your Post CODE");
    return false;
}
if (!g.match(regPostcode))
{
    alert("That Post Code is incorrect");
    return false;
}

As @Shiplu said, there is not uniform regex that will work for Post codes for every countries. 正如@Shiplu所说,没有适用于每个国家/地区的邮政编码的统一正则表达式。 You should make sure you want to block form submission from people living in some other countries. 您应该确保要阻止来自其他一些国家/地区的人提交表单。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM