I need to add a validation on the country field in all place where it can be used.
For registration or address editing it work fine but in checkout I tried several method but nothing worked. I want the validation on the field of the new shipping address form.
- I add my validation in an js file
countryValidation.js
:
Same script for registration or edit address and it work fine
define([
'jquery',
'jquery/ui',
'mage/validation',
'mage/translate',
'domReady!'
], function($){
'use strict';
return function(validator) {
$.validator.addMethod(
"validate-country",
function(value, element) {
if (value === "FR") {
var zipValue = $('input[name="postcode"]').val();
if (zipValue) {
return !(zipValue.startsWith("97") || zipValue.startsWith("98"));
}
}
return true;
},
$.mage.__("You cannot choose France for DOM-TOM Zip Code")
);
return validator;
}
});
- I registered it in
requirejs-config.js
in my module :
var config = {
config: {
mixins: {
'Magento_Ui/js/lib/validation/validator': {
'Gone_Customer/js/countryValidation': true
}
}
}
};
- For adding validation to checkout method I tried different method
-> Method A : With a plugin
class AddCountryValidation
{
public function afterProcess(
MagentoCheckoutBlockCheckoutLayoutProcessor $subject,
array $jsLayout
) {
// Country ID
$jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['shipping-address-fieldset']['children']['country_id']['validation']['validate-country'] = true;
return $jsLayout;
}
}
-> Method B : add validation rule in attribute
In customer_eav_attribute
in attribute country_id
for validate_rules
I added {"validate-country": true}
When I validate the form I have no validation error when I should have one.
Can you tell me if I’m missing something please?
2
Answers
Thank you for your response in the meantime I found something that worked. I had to do a seperate js validation only for checkout :
And in my mixin I change
Magento_Ui/js/lib/validation/validator
forMagento_Ui/js/lib/validation/rules
then my plugin method was working !Please try this
I have used return false you can modify according to your need.Tested on version 2.2.2