javascript validate zip regular expression
Thanks guys. I take your advice and modify the script as following. Now 开发者_如何学Cit 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()
and use .after()
or .before()
and not .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
and .val needs to be .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". Also, the var
is useless unless within a function scope.
(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. In CMS's example it's still a global unless you're taking the snippet and using it in an actual function.
精彩评论