如何验证邮政编码文本字段并添加 HTML 以防提交表单出错?
How to validate a zipcode text field and add HTML in case of error on submitting the form?
如果输入的邮政编码不正确,下面的 jQuery 代码会通过附加更改事件来提醒用户。我想验证在着陆页表单的文本字段中输入的邮政编码,并添加一些 HTML 以防提交表单出错。能否指导我如何操作。
HTML 输入:
<div class="ff-el-input--content"><input type="text" name="address_1[zip]" id="ff_241_address_1_zip_" class="ff-el-form-control" placeholder="Zip"></div>
jQuery 验证:
jQuery("input:text[name='address_1[zip]']").change(function(e) {
if (!jQuery(this).val().match(/^\d{5}(?:[-\s]\d{4})?$/)) {
alert("Please enter a valid zip code");
jQuery("input[name='address_1[zip]']").val("");
return false;
}
});
当验证失败时,我需要在input text
字段之后添加下面的div。
<div class="error text-danger">This field is required</div>
提交元素:
<button type="submit" class="ff-btn ff-btn-submit ff-btn-lg">Submit</button>
显示部分表格的图片:
您需要的是函数 after()
和 remove()
。
jQuery("input:text[name='address_1[zip]']").change(function(e) {
if (!jQuery(this).val().match(/^\d{5}(?:[-\s]\d{4})?$/)) {
alert("Please enter a valid zip code");
jQuery("input[name='address_1[zip]']").val("");
if ($('.error').length == 0) {
$(this).after('<div class="error text-danger">This field is required</div>');
}
} else {
$('.error').remove();
}
});
如果输入的邮政编码不正确,下面的 jQuery 代码会通过附加更改事件来提醒用户。我想验证在着陆页表单的文本字段中输入的邮政编码,并添加一些 HTML 以防提交表单出错。能否指导我如何操作。
HTML 输入:
<div class="ff-el-input--content"><input type="text" name="address_1[zip]" id="ff_241_address_1_zip_" class="ff-el-form-control" placeholder="Zip"></div>
jQuery 验证:
jQuery("input:text[name='address_1[zip]']").change(function(e) {
if (!jQuery(this).val().match(/^\d{5}(?:[-\s]\d{4})?$/)) {
alert("Please enter a valid zip code");
jQuery("input[name='address_1[zip]']").val("");
return false;
}
});
当验证失败时,我需要在input text
字段之后添加下面的div。
<div class="error text-danger">This field is required</div>
提交元素:
<button type="submit" class="ff-btn ff-btn-submit ff-btn-lg">Submit</button>
显示部分表格的图片:
您需要的是函数 after()
和 remove()
。
jQuery("input:text[name='address_1[zip]']").change(function(e) {
if (!jQuery(this).val().match(/^\d{5}(?:[-\s]\d{4})?$/)) {
alert("Please enter a valid zip code");
jQuery("input[name='address_1[zip]']").val("");
if ($('.error').length == 0) {
$(this).after('<div class="error text-danger">This field is required</div>');
}
} else {
$('.error').remove();
}
});