Posted on

Magento 2 : How add validation validator to custom input field in checkout page?

We have to add custom form in check-money order payment method.We have to add custom validations before order placement but its not working.
please check below code

1)Create the validator:-

Custom_Checkmethod/view/frontend/web/js/model/custom-validation.js

define(
[
‘jquery’,
‘mage/validation’
],
function ($) {
‘use strict’;
return {
validate: function() {
$.validator.addMethod(
‘checkmonumber’,
function (value) {
return true;
},
$.mage.__(‘Please enter number’)
);
return true;
}
}
}
);

2)Add validator to the validators pool:-

define(
[
‘uiComponent’,
‘Magento_Checkout/js/model/payment/additional-validators’,
‘Custom_Checkmethod/js/model/custom-validation’
],
function (Component, additionalValidators, yourValidator) {
‘use strict’;
additionalValidators.registerValidator(yourValidator);
return Component.extend({});
}
);

Checkout Form :-

<fieldset data-bind=”attr: {class: ‘fieldset payment items allbank ‘ + getCode(), id: ‘payment_form_’ + getCode()}”>
<label data-bind=”attr: {for: getCode() + ‘_checknumber’}” class=”label”>
<span><!– ko i18n: ‘Check Number’–><!– /ko –></span>
</label>
<div class=”control”>
<input data-validate=”{‘required-entry’:true, ‘validate-number’:true}” type=”text” name=”payment[checknumber]” class=”input-text required-entry checkmonumber” value=””
data-bind=”attr: {
id: getCode() + ‘_checknumber’,
title: $t(‘Check Number’),
‘data-container’: getCode() + ‘-checknumber’,
‘data-validate’: JSON.stringify({‘required’:true})},
valueUpdate: ‘keyup’ “/>
</div>
</fieldset>

4)Declare the validation in the checkout layout

<page xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” layout=”1column” xsi:noNamespaceSchemaLocation=”urn:magento:framework:View/Layout/etc/page_configuration.xsd”>
<body>
<referenceBlock name=”checkout.root”>
<arguments>
<argument name=”jsLayout” xsi:type=”array”>
<item name=”components” xsi:type=”array”>
<item name=”checkout” xsi:type=”array”>
<item name=”children” xsi:type=”array”>
<item name=”steps” xsi:type=”array”>
<item name=”children” xsi:type=”array”>
<item name=”billing-step” xsi:type=”array”>
<item name=”children” xsi:type=”array”>
<item name=”payment” xsi:type=”array”>
<item name=”children” xsi:type=”array”>
<item name=”additional-payment-validators” xsi:type=”array”>
<item name=”children” xsi:type=”array”>
<!– Declare your validation. START –>
<item name=”your-validator” xsi:type=”array”>
<item name=”component” xsi:type=”string”>Custom_Checkmethod/js/view/add-validator</item>
</item>
<!– Declare your validation. END –>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</argument>
</arguments>
</referenceBlock>
</body>
</page>

when we click on place order button then add input field validation.I am not able to how to add it?please tell me how to validate input field.

Leave a Reply

Your email address will not be published.