I am coding the new PayPal Express Checkout JavaScript button so when it is clicked, some validation is run and based on the validation, the button experience is continued or suppressed.
This demo shows some validation but not exactly what I need. https://developer.paypal.com/demo/checkout/#/pattern/validation
I have this test case you can try: https://jsfiddle.net/gardavis/51kvtjax - this code uses PayPal's script: https://www.paypalobjects.com/api/checkout.js.
This is the part of the jsfiddle I am attempting to get working...
// Called when page displays
validate: function(actions) {
console.log("validate called");
actions.disable(); // Allow for validation in onClick()
paypalActions = actions; // Save for later enable()/disable() calls
},
// Called for every click on the PayPal button even if actions.disabled
onClick: function() {
console.log('onClick called');
// Do validations and if OK, continue on to PayPal popup
var zip = document.querySelector('#zipcode').value;
var isValid = zip.length >= 5;
// Issue: fix to continue if valid, suppress popup if invalid
if (isValid) {
document.querySelector('#msg').style.display = 'none';
paypalActions.enable();
// TODO: Simulate click of PayPal button to display popup
} else {
document.querySelector('#msg').style.display = 'block';
paypalActions.disable(); // Too late
}
},
The validate() is called once, basically when the page is loaded. That's too early to validate. The onClick() function is called when the button is clicked and a good place to do my validation but I don't have a way to continue if valid and display the error if not.
The demo uses a checkbox event within the scope of the validate() function so it is able to enable/disable the PayPal popup (onClick() still works if disabled). The demo's onClick() simply shows/hides the error message.
Does anyone know how to do validation within onClick()?