Validate zip and display error with onBlur event
Check if zip is 5 digit number, if not then display 'zip is invalid'. I want to use onBlur event to trigger the display. But it's not working.
<script>
$(function(){
function valid_zip()
{
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" onblur="valid_zip开发者_如何学运维()">
$('#zip').blur(function()
{
var pat=/^[0-9]{5}$/;
if ( !pat.test( $(this).val() ) )
{$(this).after('<p>zip is invalid</p>');}
})
you are now using jQuery, don't do inline coding...
<input type="text" name='zip' id='zip' maxlength="5" onBlur="valid_zip()">
should just be
<input type="text" name='zip' id='zip' maxlength="5">
It should look more like this:
<script>
$(function(){
$("#zip").blur(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">
onblur
should be all lowercase.
<input type="text" name="zip" id="zip" maxlength="5" onblur="valid_zip()">
Also, why are putting valid_zip
inside $()
- you can just do:
<script>
function valid_zip()
{
var pat=/^[0-9]{5}$/;
if ( !pat.test( $('#zip').val() ) )
{
$('#zip').after('<p>zip is invalid</p>');
}
}
</script>
精彩评论