You can simply create your own element with modified validation process for this purpose. In your extension create a new file view/base/web/js/form/element/custom.js
with the following content:
define([
'Magento_Ui/js/form/element/abstract',
'Magento_Ui/js/lib/validation/validator'
], function (Abstract, validator) {
'use strict';
return Abstract.extend({
validate: function () {
var value = this.value(),
result = validator(this.validation, value, this.validationParams),
message = result.message,
isValid = result.passed;
this.error(message);
this.bubble('error', message);
if (!isValid) {
this.source.set('params.invalid', true);
alert('Please, specify a delivery date');
}
return {
valid: isValid,
target: this
};
}
});
});
Then, in LayoutProcessorPlugin change the 'component' value to the newly created element:
'component' => 'Modules_Deliverydate/js/form/element/custom'
In that way, you are able to extend the Abstract element and modify the "validate" method by removing field visibility checking etc. In this example the error message is being shown as an alert but you can use whatever you want.
Hope it will help.
To add validation on the zip field we should overwirte Magento_Checkout/layout/checkout_index_index.xml
and add this code :
<item name="validation" xsi:type="array">
<item name="validate-zip-us" xsi:type="string">true</item>
</item>
Like this
<item name="postcode" xsi:type="array">
<item name="sortOrder" xsi:type="string">75</item>
<!-- post-code field has custom UI component -->
<item name="component" xsi:type="string">Magento_Ui/js/form/element/post-code</item>
<item name="validation" xsi:type="array">
<item name="required-entry" xsi:type="string">true</item>
<item name="validate-zip-us" xsi:type="string">true</item>
</item>
</item>
zip-range
for example is a already defined rule in rules.js
.
We can overwrite this rule or we can create another rule according to our needs in this location:Theme\Theme\Magento_Ui\web\js\lib\validation\rules.js
>
Best Answer
Basically, you need to register your custom validation method and then use it for your field in
system.xml
file.Define your validation method:
And use it for your field in
system.xml
:Search for "validator.addMethod" in the Magento 2 core code, there are a bunch of examples there showing more complex use cases.