1

I am using the following code on a form to use the validation.js library to validate the form. One of the validation files uses ./rules.js to extend the rules used within the validator which I have managed to overwrite. However {"validation":{}} is not the file that uses it. Can some body please show me?

I have not set a requirejs config in the module that I am doing this from.

I want to add a basic rule that comes back true or false every time just to start from somewhere.

data-mage-init='{"validation": {}}

1 Answer 1

0

It's hard to answer your question without creating an example. So I suppose that you need to add your custom validation rule into your custom payment method in Magento 2.

Then, your method render js will look like this:

/**
 * Copyright © 2017 StackOverflow. All rights reserved.
 * See COPYING.txt for license details.
 */
/*browser:true*/
/*global define*/
define(
    [
        'jquery',
        'ko',
        'Magento_Checkout/js/view/payment/default',
        'mage/validation'
    ],
    function ($, ko, Component) {
        'use strict';

        $.validator.addMethod('validate-input-one', function (value) {
            return (value === $('#hidden-input-one').val());
        }, 'You have to select input 1 before place order.');

        $.validator.addMethod('validate-input-two', function (value) {
            return (value === $('#hidden-input-two').val());
        }, 'You have to select input 2 before place order.');

        return Component.extend({

            ...

            /**
             * Custompayment form validation
             *
             * @returns {Boolean}
             */
            validate: function () {
                var form = 'form[data-role=custompayment-form]';
                return $(form).validation() && $(form).validation('isValid');
            },

            ...

        });
    }
);

Now, in your custom payment method template file:

<input type="text"
       id="input-one"
       name="payment[input-one]"
       data-validate="{required:true, 'validate-input-one': true}"
       aria-haspopup="false"
       aria-autocomplete="both"
       autocomplete="off"
       class="input-text"/>
<input type="hidden" id="hidden-input-one" data-bind="value: inputOne" />

As you see, whenever the value attribute of #hidden-input-one is empty, #input-one will not pass the validation.

CONCLUSION

mage/validation is the key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.