You are viewing limited content. For full access, please sign in.

Question

Question

Forms Address Block Limit Zip to 5 Digits

asked on November 30, 2020

Looking for a little input.  I am using an address block in Forms and I want to not only set the limit of the Zip Code to 5 but I want to limit the input to digits.

 

I can set the max length to 5 characters with $(".Postal").attr("maxlength", 5); in the JavaScript.

 

I can limit it to numbers using $(".Postal").attr({"type", "number"); BUT that puts up and down arrows at the end of the field input and I don't like that.

 

I have been playing around with $(".Postal").attr("pattern", "\d{5})"); and multiple variations such as [0-9] but [0-9] always tells me it is invalid input no matter what I put in the field.  And other variations I have tried always break the rest of the javascript for the state and county fields.

 

Does anyone out there have a simple way to limit the Zip in an address block to 5 digits?

 

Thanks.

1 0

Answer

SELECTED ANSWER
replied on December 1, 2020 Show version history

Try:

$(".Postal").attr("pattern", "\\d{5}");

2 0

Replies

replied on December 1, 2020

Thanks Aaron,

 

I tried various options with \\d and options with {5} but guess I never got the right combination together.  I have your suggestion a try and it worked great!

1 0
replied on September 10

I'm using below code and if the validation fails, the form is not re-focusing to the Zip code field. Instead it is submitting the form, any thoughts? 

//ZipCode Validation
      // Change the label text for the Postal field
    $(".Postal").siblings().text('Zip Code');

    // Regex for exactly 5 digits
    var regex = /^\d{5}$/; 

    // Validate the Postal field on input
    $('.Postal').on('input', function() {
        var inputVal = $(this).val(); // Get the current value of the input field

        // Clear any previous error messages
        $('#postalErrorMessage').remove(); 

        // Validate against the regex
        if (!regex.test(inputVal)) {
            $(this).after('<div id="postalErrorMessage" style="color:red;">Invalid ZIP code. Enter exactly 5 digits.</div>');
        }
    });
  // Validate on submit
    $('.SubmitButton').on('click', function (event) {
    const zipVal = $('.Postal').val();
    const regex = /^\d{5}$/;

    if (!regex.test(zipVal)) {
        event.preventDefault();
        $('.Postal').focus();
        $('#postalErrorMessage').remove();
        $('.Postal').after('<div id="postalErrorMessage" style="color:red;">ZIP code must be exactly 5 digits.</div>');
        return false;
        }
    });

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.