Home > Enterprise >  How to validate a zipcode text field and add HTML in case of error on submitting the form?
How to validate a zipcode text field and add HTML in case of error on submitting the form?

Time:12-10

The jQuery code below alerts the user in case of incorrect zip code entered by attaching the change event to it. I would like to validate zip code entered in the text field on form in a landing page and add a bit of HTML in case of error on submitting the form. Could you please guide me on how to do it.

HTML for the input:

<div ><input type="text" name="address_1[zip]" id="ff_241_address_1_zip_"  placeholder="Zip"></div>

jQuery to validate:

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;                        
    }        
});

When validation fails, I need to add the div below to right after the input text field. <div >This field is required</div>

Submit element:

<button type="submit" >Submit</button>

Image showing part of the form: enter image description here

CodePudding user response:

What you need are the functions after() and 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 >This field is required</div>');
    }
  } else {
    $('.error').remove();
  }
});
  • Related