简体   繁体   English

javascript验证zip正则表达式

[英]javascript validate zip regular expression

Thanks guys. 多谢你们。 I take your advice and modify the script as following. 我接受您的建议,并按如下所示修改了脚本。 Now it seems working. 现在看来可行。

<script src="jquery-1.4.2.min.js" type="text/javascript"></script>   
<script>
$(function(){
var pat=/^[0-9]{5}$/;
if ( !pat.test(   $('#zip').val()   ) )
{$('#zip').after('<p>zip is invalid</p>');}
})
</script>

zip (US only) <input type="text" name='zip' id='zip' maxlength="5">

.val needs to be .val() .val必须是.val()
and use .after() or .before() and not .append() 并使用.before() .after().before()而不是.append()

var pattern = /^[0-9]{5}$/;
if (!pattern.test($('#zip').val())) {
  $('#zip').after('<p>zip is invalid</p>');
}

zip is invalid should be enclosed in quotes zip无效,应用引号引起来

and .val needs to be .val() 和.val必须是.val()

<script>
  pattern=/^[0-9]{5}$/;
  if (!pattern.test( $('#zip').val() ) ) 
  {
    $('#zip').val($('<p>',{html: "zip is invalid"}));
  }
</script>

Space it out so you can see what's wrong.. 将其间隔开,以便您查看问题所在。

pattern=/^[0-9]{5}$/;
if (
   !pattern.test(   $('#zip').val()  ) 
)
{
    $('#zip').after(
         $('<p>',{html: "zip is invalid"})
    );
}

val() and "zip is valid". val()和“ zip有效”。 Also, the var is useless unless within a function scope. 另外,除非在函数范围内,否则var是无用的。

(function() {
    var pattern=/^[0-9]{5}$/;
    if (
       !pattern.test(   $('#zip').val()  ) 
    )
    {
        $('#zip').after(
             $('<p>',{html: "zip is invalid"})
        );
    }
})();

Now pattern is local to that function only and nothing else. 现在, pattern仅在该函数中是本地的,而没有别的。 In CMS's example it's still a global unless you're taking the snippet and using it in an actual function. 在CMS的示例中,它仍然是全局的,除非您要使用摘录并将其用于实际功能中。

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

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