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>