0

I am trying to do a call to a service to check if a zipcode is valid... and if it is not then show a parsley error 'invalid Zipcode'.

I have done custom parsley validation before, and I have done ajax requests before but I am not sure how to combine the two, to do an asynchronous parsley validation.

Note: validation is triggered on 'focusout' so just press tab or click out to trigger validation

Desired Behavior:

If the Zipcode entered does not correlate to a state. it should give error

Valid Zipcode: 222222 = VA

Valid Zipcode: 444444 = OH

Invalid Zipcode: 111111 = '' //Display parsley error

Current Behavior:

Invalid Zipcode: 111111 = '' //DOES NOT Display parsley error

Related Stackoverflow Questions, but wasn't able to figure out a solution from:

I have looked at some other Posts, but still can't figure it out: Other posts:

1) Custom Parsley.js asynchronous validator loops twice

2) How to return value from an asynchronous callback function?

Notes about the code:

Right now I just have a function that is triggered on keyup: $('#Zipcode').keyup(function (){... this needs to be replaced with a window.Parsley.addAsyncValidator(... method call instead.

//Only Allow Numbers
document.querySelector('#Zipcode').addEventListener("input", function (event) {
    this.value = this.value.replace(/[^0-9]/g, "").substring(0, 5);
});

$('#Zipcode').keyup(function () {
            var zipApiUrl = '//api.zippopotam.us/us/';
            var zip_in = $(this);
            if ((zip_in.val().length === 5)) {

                // Make HTTP Request
                $.ajax({
                    url: zipApiUrl + zip_in.val(),
                    cache: false,
                    dataType: "json",
                    type: "GET",
                    success: function (result, success) {
                        $('#zipState').val(result['places'][0]['state abbreviation']);
                    },
                    error: function (result, success) {
                        $('#zipState').val('');
                    }
                });
            }
        });
        
//window.Parsley.addAsyncValidator('validZipcodeCheck',
form .parsley-error{ 
  border: 2px solid #ba0000 !important; 
  }
form .parsley-errors-list{ margin-top: 0; margin-bottom: 0; color: red;}
<script
  src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.7.2/parsley.js"></script>


<form data-parsley-validate>


<label for="Zipcode">ZIP CODE</label>
<input type="tel" 
       id="Zipcode" name="Zipcode"
       autocomplete="on"
       required="" data-parsley-required-message="Required"
       data-parsley-minlength="5" data-parsley-minlength-message="Invalid 5-Digit Zip"
       data-parsley-trigger="focusout"
       data-parsley-validZipcodeCheck=""  data-parsley-validZipcodeCheck-message="Invalid Zipcode"
       />     
       
<div>
  <label>State</label>
  <input disabled id="zipState" name="State" />
</div>

<!--input type="submit" value="SUBMIT Zipcode" /-->

<form>
Nick Timmer
  • 425
  • 2
  • 12
  • I think this is pretty much exactly what i want: http://parsleyjs.org/doc/examples/ajax.html just have to digest all of it – Nick Timmer Jan 29 '18 at 19:12

1 Answers1

0

This works... but there are unpleasant side effects...

Mainly when I do it this way I can no longer do $('form').parsley().validate() - which used to return true/false now always returns null. So as a result to perform ajax submit I have to create a listener

like so:

window.Parsley.on('form:submit', function () { $.ajax(...) })

instead of how I usually see it done:

$(leadFormEle).on('submit', function (ele) {
ele.preventDefault();
$(this).parsley().validate();
if ( $(this).parsley().isValid() ) { $.ajax(...) }
});

//Only Allow Numbers
 document.querySelector('#zipcode').addEventListener("input", function (event) {
    this.value = this.value.replace(/[^0-9]/g, "").substring(0, 5);
});

Parsley.addValidator('zip', {
            validateString: function (value) {
                // Zippopotam.us returns a status 404 for incorrect zip codes,
                // so we simply return the ajax request:
                return $.ajax({
                    url: '//www.zippopotam.us/us/' + value,
                    success: function (result, success) {
                        $('#zipState').val(result['places'][0]['state abbreviation']);
                    },
                    error: function (result, success) {
                        $('#zipState').val('');
                    }
                })
            }
        });
form .parsley-error{ 
  border: 2px solid #ba0000 !important; 
  }
form .parsley-errors-list{ margin-top: 0; margin-bottom: 0; color: red;}
<script
  src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parsley.js/2.8.0/parsley.js"></script>


<form data-parsley-validate>


<label for="zipcode">ZIP CODE</label>
<input type="tel" 
       id="zipcode" name="zipcode"
       autocomplete="on"
       required="" data-parsley-required-message="Required"
       data-parsley-minlength="5" data-parsley-minlength-message="Invalid 5-Digit Zip"
       data-parsley-trigger="focusout"
       data-parsley-validZipcodeCheck=""  data-parsley-validZipcodeCheck-message="Invalid Zipcode"
       data-parsley-zip="us"
       data-parsley-zip-message="Invalid US Zip"
       maxlength=5
       />     
       
<div>
  <label>State</label>
  <input disabled id="zipState" name="State" />
</div>

<!--input type="submit" value="SUBMIT Zipcode" /-->

<form>
Nick Timmer
  • 425
  • 2
  • 12