validation.js 10.2 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/* global BASE_URL, alertAlreadyDisplayed */
(function (factory) {
    'use strict';

    if (typeof define === 'function' && define.amd) {
        define([
            'jquery',
            'underscore',
            'Magento_Ui/js/modal/alert',
            'jquery/ui',
            'jquery/validate',
            'mage/translate',
            'mage/validation'
        ], factory);
    } else {
        factory(jQuery);
    }
}(function ($, _, alert) {
    'use strict';

    $.extend(true, $.validator.prototype, {
        /**
         * Focus invalid fields
         */
        focusInvalid: function () {
            if (this.settings.focusInvalid) {
                try {
                    $(this.errorList.length && this.errorList[0].element || [])
                        .focus()
                        .trigger('focusin');
                } catch (e) {
                    // ignore IE throwing errors when focusing hidden elements
                }
            }
        },

        /**
         * Elements.
         */
        elements: function () {
            var validator = this,
                rulesCache = {};

            // select all valid inputs inside the form (no submit or reset buttons)
            return $(this.currentForm)
                .find('input, select, textarea')
                .not(this.settings.forceIgnore)
                .not(':submit, :reset, :image, [disabled]')
                .not(this.settings.ignore)
                .filter(function () {
                    if (!this.name && validator.settings.debug && window.console) {
                        console.error('%o has no name assigned', this);
                    }

                    // select only the first element for each name, and only those with rules specified
                    if (this.name in rulesCache || !validator.objectLength($(this).rules())) {
                        return false;
                    }

                    rulesCache[this.name] = true;

                    return true;
                });
        }
    });

    $.extend($.fn, {
        /**
         * ValidationDelegate overridden for those cases where the form is located in another form,
         *     to avoid not correct working of validate plug-in
         * @override
         * @param {String} delegate - selector, if event target matched against this selector,
         *     then event will be delegated
         * @param {String} type - event type
         * @param {Function} handler - event handler
         * @return {Element}
         */
        validateDelegate: function (delegate, type, handler) {
            return this.on(type, $.proxy(function (event) {
                var target = $(event.target),
                    form = target[0].form;

                if (form && $(form).is(this) && $.data(form, 'validator') && target.is(delegate)) {
                    return handler.apply(target, arguments);
                }
            }, this));
        }
    });

    $.widget('mage.validation', $.mage.validation, {
        options: {
            messagesId: 'messages',
            forceIgnore: '',
            ignore: ':disabled, .ignore-validate, .no-display.template, ' +
                ':disabled input, .ignore-validate input, .no-display.template input, ' +
                ':disabled select, .ignore-validate select, .no-display.template select, ' +
                ':disabled textarea, .ignore-validate textarea, .no-display.template textarea',
            errorElement: 'label',
            errorUrl: typeof BASE_URL !== 'undefined' ? BASE_URL : null,

            /**
             * @param {HTMLElement} element
             */
            highlight: function (element) {
                if ($.validator.defaults.highlight && $.isFunction($.validator.defaults.highlight)) {
                    $.validator.defaults.highlight.apply(this, arguments);
                }
                $(element).trigger('highlight.validate');
            },

            /**
             * @param {HTMLElement} element
             */
            unhighlight: function (element) {
                if ($.validator.defaults.unhighlight && $.isFunction($.validator.defaults.unhighlight)) {
                    $.validator.defaults.unhighlight.apply(this, arguments);
                }
                $(element).trigger('unhighlight.validate');
            }
        },

        /**
         * Validation creation
         * @protected
         */
        _create: function () {
            if (!this.options.submitHandler && $.type(this.options.submitHandler) !== 'function') {
                if (!this.options.frontendOnly && this.options.validationUrl) {
                    this.options.submitHandler = $.proxy(this._ajaxValidate, this);
                } else {
                    this.options.submitHandler = $.proxy(this._submit, this);
                }
            }
            this.element.on('resetElement', function (e) {
                $(e.target).rules('remove');
            });
            this._super('_create');
        },

        /**
         * ajax validation
         * @protected
         */
        _ajaxValidate: function () {
            $.ajax({
                url: this.options.validationUrl,
                type: 'POST',
                dataType: 'json',
                data: this.element.serialize(),
                context: $('body'),
                success: $.proxy(this._onSuccess, this),
                error: $.proxy(this._onError, this),
                showLoader: true,
                dontHide: false
            });
        },

        /**
         * Process ajax success.
         *
         * @protected
         * @param {Object} response
         */
        _onSuccess: function (response) {
            if (!response.error) {
                this._submit();
            } else {
                this._showErrors(response);
                $(this.element[0]).trigger('afterValidate.error');
                $('body').trigger('processStop');
            }
        },

        /**
         * Submitting a form.
         * @private
         */
        _submit: function () {
            $(this.element[0]).trigger('afterValidate.beforeSubmit');
            this.element[0].submit();
        },

        /**
         * Displays errors after backend validation.
         *
         * @param {Object} data - Data that came from backend.
         */
        _showErrors: function (data) {
            $('body').notification('clear')
                .notification('add', {
                    error: data.error,
                    message: data.message,

                    /**
                     * @param {*} message
                     */
                    insertMethod: function (message) {
                        $('.messages:first').html(message);
                    }
                });
        },

        /**
         * Tries to retrieve element either by id or by inputs' name property.
         * @param {String} code - String to search by.
         * @returns {jQuery} jQuery element.
         */
        _getByCode: function (code) {
            var parent = this.element[0],
                element;

            element = parent.querySelector('#' + code) || parent.querySelector('input[name=' + code + ']');

            return $(element);
        },

        /**
         * Process ajax error
         * @protected
         */
        _onError: function () {
            $(this.element[0]).trigger('afterValidate.error');
            $('body').trigger('processStop');

            if (this.options.errorUrl) {
                location.href = this.options.errorUrl;
            }
        }
    });

    _.each({
        'validate-greater-zero-based-on-option': [
            function (v, el) {
                var optionType = $(el)
                    .closest('.form-list')
                    .prev('.fieldset-alt')
                    .find('select.select-product-option-type'),
                    optionTypeVal = optionType.val();

                v = Number(v) || 0;

                if (optionType && (optionTypeVal == 'checkbox' || optionTypeVal == 'multi') && v <= 0) { //eslint-disable-line
                    return false;
                }

                return true;
            },
            $.mage.__('Please enter a number greater 0 in this field.')
        ],
        'validate-rating': [
            function () {
                var ratings = $('#detailed_rating').find('.field-rating'),
                    noError = true;

                ratings.each(function (index, rating) {
                    noError = noError && $(rating).find('input:checked').length > 0;
                });

                return noError;
            },
            $.mage.__('Please select one of each ratings above.')
        ],
        'validate-downloadable-file': [
            function (v, element) {
                var elmParent = $(element).parent(),
                    linkType = elmParent.find('input[value="file"]'),
                    newFileContainer;

                if (linkType.is(':checked') && (v === '' || v === '[]')) {
                    newFileContainer = elmParent.find('.new-file');

                    if (!alertAlreadyDisplayed && (newFileContainer.empty() || newFileContainer.is(':visible'))) {
                        window.alertAlreadyDisplayed = true;
                        alert({
                            content: $.mage.__('There are files that were selected but not uploaded yet. ' +
                            'Please upload or remove them first')
                        });
                    }

                    return false;
                }

                return true;
            },
            'Please upload a file.'
        ],
        'validate-downloadable-url': [
            function (v, element) {
                var linkType = $(element).parent().find('input[value="url"]');

                if (linkType.is(':checked') && v === '') {
                    return false;
                }

                return true;
            },
            $.mage.__('Please specify Url.')
        ]
    }, function (rule, i) {
        rule.unshift(i);
        $.validator.addMethod.apply($.validator, rule);
    });

    return $.mage.validation;
}));