yii.activeForm.js 22.7 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9 10 11 12 13
/**
 * Yii form widget.
 *
 * This is the JavaScript widget used by the yii\widgets\ActiveForm widget.
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
(function ($) {

Qiang Xue committed
14 15 16 17 18 19 20 21 22 23
    $.fn.yiiActiveForm = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.yiiActiveForm');
            return false;
        }
    };
Qiang Xue committed
24

25
    // NOTE: If you change any of these defaults, make sure you update yii\widgets\ActiveForm::getClientOptions() as well
Qiang Xue committed
26
    var defaults = {
27 28
        // whether to encode the error summary
        encodeErrorSummary: true,
Qiang Xue committed
29
        // the jQuery selector for the error summary
30
        errorSummary: '.error-summary',
Qiang Xue committed
31 32 33
        // whether to perform validation before submitting the form.
        validateOnSubmit: true,
        // the container CSS class representing the corresponding attribute has validation error
34
        errorCssClass: 'has-error',
Qiang Xue committed
35
        // the container CSS class representing the corresponding attribute passes validation
36
        successCssClass: 'has-success',
Qiang Xue committed
37 38
        // the container CSS class representing the corresponding attribute is being validated
        validatingCssClass: 'validating',
39 40 41 42
        // the GET parameter name indicating an AJAX-based validation
        ajaxParam: 'ajax',
        // the type of data that you're expecting back from the server
        ajaxDataType: 'json',
Qiang Xue committed
43 44 45 46 47 48 49 50
        // the URL for performing AJAX-based validation. If not set, it will use the the form's action
        validationUrl: undefined,
        // a callback that is called before submitting the form. The signature of the callback should be:
        // function ($form) { ...return false to cancel submission...}
        beforeSubmit: undefined,
        // a callback that is called before validating each attribute. The signature of the callback should be:
        // function ($form, attribute, messages) { ...return false to cancel the validation...}
        beforeValidate: undefined,
51 52 53
        // a callback that is called before validation starts (This callback is only called when the form is submitted). This signature of the callback should be:
        // function($form, data) { ...return false to cancel the validation...}
        beforeValidateAll: undefined,
Qiang Xue committed
54 55 56
        // a callback that is called after an attribute is validated. The signature of the callback should be:
        // function ($form, attribute, messages)
        afterValidate: undefined,
57 58 59
        // a callback that is called after all validation has run (This callback is only called when the form is submitted). The signature of the callback should be:
        // function ($form, data, messages)
        afterValidateAll: undefined,
60 61 62 63 64
        // a pre-request callback function on AJAX-based validation. The signature of the callback should be:
        // function ($form, jqXHR, textStatus)
        ajaxBeforeSend: undefined,
        // a function to be called when the request finishes on AJAX-based validation. The signature of the callback should be:
        // function ($form, jqXHR, textStatus)
65
        ajaxComplete: undefined
Qiang Xue committed
66
    };
Qiang Xue committed
67

68
    // NOTE: If you change any of these defaults, make sure you update yii\widgets\ActiveField::getClientOptions() as well
Qiang Xue committed
69
    var attributeDefaults = {
70 71
        // a unique ID identifying an attribute (e.g. "loginform-username") in a form
        id: undefined,
Qiang Xue committed
72 73 74 75
        // attribute name or expression (e.g. "[0]content" for tabular input)
        name: undefined,
        // the jQuery selector of the container of the input field
        container: undefined,
76
        // the jQuery selector of the input field under the context of the container
Qiang Xue committed
77
        input: undefined,
78 79
        // the jQuery selector of the error tag under the context of the container
        error: '.help-block',
80 81
        // whether to encode the error
        encodeError: true,
Qiang Xue committed
82
        // whether to perform validation when a change is detected on the input
83
        validateOnChange: true,
84
        // whether to perform validation when the input loses focus
85
        validateOnBlur: true,
Qiang Xue committed
86 87 88 89 90 91 92 93 94 95 96 97 98
        // whether to perform validation when the user is typing.
        validateOnType: false,
        // number of milliseconds that the validation should be delayed when a user is typing in the input field.
        validationDelay: 200,
        // whether to enable AJAX-based validation.
        enableAjaxValidation: false,
        // function (attribute, value, messages), the client-side validation function.
        validate: undefined,
        // status of the input field, 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating
        status: 0,
        // the value of the input
        value: undefined
    };
Qiang Xue committed
99

Qiang Xue committed
100 101 102 103 104 105 106
    var methods = {
        init: function (attributes, options) {
            return this.each(function () {
                var $form = $(this);
                if ($form.data('yiiActiveForm')) {
                    return;
                }
Qiang Xue committed
107

Qiang Xue committed
108 109 110 111
                var settings = $.extend({}, defaults, options || {});
                if (settings.validationUrl === undefined) {
                    settings.validationUrl = $form.prop('action');
                }
112

Qiang Xue committed
113 114
                $.each(attributes, function (i) {
                    attributes[i] = $.extend({value: getValue($form, this)}, attributeDefaults, this);
115
                    watchAttribute($form, attributes[i]);
Qiang Xue committed
116
                });
117

Qiang Xue committed
118 119 120 121 122 123
                $form.data('yiiActiveForm', {
                    settings: settings,
                    attributes: attributes,
                    submitting: false,
                    validated: false
                });
Qiang Xue committed
124

Qiang Xue committed
125 126 127 128 129
                /**
                 * Clean up error status when the form is reset.
                 * Note that $form.on('reset', ...) does work because the "reset" event does not bubble on IE.
                 */
                $form.bind('reset.yiiActiveForm', methods.resetForm);
Qiang Xue committed
130

Qiang Xue committed
131 132 133 134
                if (settings.validateOnSubmit) {
                    $form.on('mouseup.yiiActiveForm keyup.yiiActiveForm', ':submit', function () {
                        $form.data('yiiActiveForm').submitObject = $(this);
                    });
135
                    $form.on('submit.yiiActiveForm', methods.submitForm);
Qiang Xue committed
136 137 138
                }
            });
        },
Qiang Xue committed
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
        // add a new attribute to the form dynamically.
        // please refer to attributeDefaults for the structure of attribute
        add: function (attribute) {
            var $form = $(this);
            attribute = $.extend({value: getValue($form, attribute)}, attributeDefaults, attribute);
            $form.data('yiiActiveForm').attributes.push(attribute);
            watchAttribute($form, attribute);
        },

        // remove the attribute with the specified ID from the form
        remove: function (id) {
            var $form = $(this),
                attributes = $form.data('yiiActiveForm').attributes,
                index = -1,
                attribute;
            $.each(attributes, function (i) {
                if (attributes[i]['id'] == id) {
                    index = i;
                    attribute = attributes[i];
                    return false;
                }
            });
            if (index >= 0) {
                attributes.splice(index, 1);
                unwatchAttribute($form, attribute);
            }
            return attribute;
        },

        // find an attribute config based on the specified attribute ID
        find: function (id) {
            var attributes = $(this).data('yiiActiveForm').attributes, result;
            $.each(attributes, function (i) {
                if (attributes[i]['id'] == id) {
                    result = attributes[i];
                    return false;
                }
            });
            return result;
        },

Qiang Xue committed
181 182
        destroy: function () {
            return this.each(function () {
Qiang Xue committed
183
                $(this).unbind('.yiiActiveForm');
Qiang Xue committed
184 185 186
                $(this).removeData('yiiActiveForm');
            });
        },
Qiang Xue committed
187

Qiang Xue committed
188 189 190
        data: function () {
            return this.data('yiiActiveForm');
        },
Qiang Xue committed
191

Qiang Xue committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205
        submitForm: function () {
            var $form = $(this),
                data = $form.data('yiiActiveForm');
            if (data.validated) {
                if (data.settings.beforeSubmit !== undefined) {
                    if (data.settings.beforeSubmit($form) == false) {
                        data.validated = false;
                        data.submitting = false;
                        return false;
                    }
                }
                // continue submitting the form since validation passes
                return true;
            }
Qiang Xue committed
206

Qiang Xue committed
207 208 209 210
            if (data.settings.timer !== undefined) {
                clearTimeout(data.settings.timer);
            }
            data.submitting = true;
211 212 213 214 215
            
            if (data.settings.beforeValidateAll && !data.settings.beforeValidateAll($form, data)) {
                data.submitting = false;
                return false;
            }
Qiang Xue committed
216 217 218 219 220 221 222
            validate($form, function (messages) {
                var errors = [];
                $.each(data.attributes, function () {
                    if (updateInput($form, this, messages)) {
                        errors.push(this.input);
                    }
                });
223 224 225 226 227
                
                if (data.settings.afterValidateAll) {
                    data.settings.afterValidateAll($form, data, messages);
                }
                
Qiang Xue committed
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
                updateSummary($form, messages);
                if (errors.length) {
                    var top = $form.find(errors.join(',')).first().offset().top;
                    var wtop = $(window).scrollTop();
                    if (top < wtop || top > wtop + $(window).height) {
                        $(window).scrollTop(top);
                    }
                } else {
                    data.validated = true;
                    var $button = data.submitObject || $form.find(':submit:first');
                    // TODO: if the submission is caused by "change" event, it will not work
                    if ($button.length) {
                        $button.click();
                    } else {
                        // no submit button in the form
                        $form.submit();
                    }
                    return;
                }
                data.submitting = false;
            }, function () {
                data.submitting = false;
            });
            return false;
        },
Qiang Xue committed
253

Qiang Xue committed
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        resetForm: function () {
            var $form = $(this);
            var data = $form.data('yiiActiveForm');
            // Because we bind directly to a form reset event instead of a reset button (that may not exist),
            // when this function is executed form input values have not been reset yet.
            // Therefore we do the actual reset work through setTimeout.
            setTimeout(function () {
                $.each(data.attributes, function () {
                    // Without setTimeout() we would get the input values that are not reset yet.
                    this.value = getValue($form, this);
                    this.status = 0;
                    var $container = $form.find(this.container);
                    $container.removeClass(
                        data.settings.validatingCssClass + ' ' +
                            data.settings.errorCssClass + ' ' +
                            data.settings.successCssClass
                    );
                    $container.find(this.error).html('');
                });
                $form.find(data.settings.summary).hide().find('ul').html('');
            }, 1);
        }
    };
Qiang Xue committed
277

Qiang Xue committed
278 279 280 281 282 283
    var watchAttributes = function ($form, attributes) {
        $.each(attributes, function (i, attribute) {
            var $input = findInput($form, attribute);
            if (attribute.validateOnChange) {
                $input.on('change.yiiActiveForm',function () {
                    validateAttribute($form, attribute, false);
284 285 286 287
                });
            }
            if (attribute.validateOnBlur) {
                $input.on('blur.yiiActiveForm', function () {
Qiang Xue committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301
                    if (attribute.status == 0 || attribute.status == 1) {
                        validateAttribute($form, attribute, !attribute.status);
                    }
                });
            }
            if (attribute.validateOnType) {
                $input.on('keyup.yiiActiveForm', function () {
                    if (attribute.value !== getValue($form, attribute)) {
                        validateAttribute($form, attribute, false);
                    }
                });
            }
        });
    };
Qiang Xue committed
302

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    var watchAttribute = function ($form, attribute) {
        var $input = findInput($form, attribute);
        if (attribute.validateOnChange) {
            $input.on('change.yiiActiveForm',function () {
                validateAttribute($form, attribute, false);
            });
        }
        if (attribute.validateOnBlur) {
            $input.on('blur.yiiActiveForm', function () {
                if (attribute.status == 0 || attribute.status == 1) {
                    validateAttribute($form, attribute, !attribute.status);
                }
            });
        }
        if (attribute.validateOnType) {
            $input.on('keyup.yiiActiveForm', function () {
                if (attribute.value !== getValue($form, attribute)) {
                    validateAttribute($form, attribute, false);
                }
            });
        }
    };

    var unwatchAttribute = function ($form, attribute) {
        findInput($form, attribute).off('.yiiActiveForm');
    };

Qiang Xue committed
330 331
    var validateAttribute = function ($form, attribute, forceValidate) {
        var data = $form.data('yiiActiveForm');
Qiang Xue committed
332

Qiang Xue committed
333 334 335 336 337 338 339 340 341 342 343 344
        if (forceValidate) {
            attribute.status = 2;
        }
        $.each(data.attributes, function () {
            if (this.value !== getValue($form, this)) {
                this.status = 2;
                forceValidate = true;
            }
        });
        if (!forceValidate) {
            return;
        }
Qiang Xue committed
345

Qiang Xue committed
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
        if (data.settings.timer !== undefined) {
            clearTimeout(data.settings.timer);
        }
        data.settings.timer = setTimeout(function () {
            if (data.submitting || $form.is(':hidden')) {
                return;
            }
            $.each(data.attributes, function () {
                if (this.status === 2) {
                    this.status = 3;
                    $form.find(this.container).addClass(data.settings.validatingCssClass);
                }
            });
            validate($form, function (messages) {
                var hasError = false;
                $.each(data.attributes, function () {
                    if (this.status === 2 || this.status === 3) {
                        hasError = updateInput($form, this, messages) || hasError;
                    }
                });
            });
        }, data.settings.validationDelay);
    };
Alex-Code committed
369 370 371 372 373 374 375 376 377
    
    /**
     * Returns an array prototype with a shortcut method for adding a new deferred.
     * The context of the callback will be the deferred object so it can be resolved like ```this.resolve()```
     * @returns Array
     */
    var deferredArray = function () {
        var array = [];
        array.add = function(callback) {
Alex-Code committed
378
            this.push(new $.Deferred(callback));
Alex-Code committed
379 380 381 382
        };
        return array;
    };
    
Qiang Xue committed
383 384 385 386 387 388 389 390 391
    /**
     * Performs validation.
     * @param $form jQuery the jquery representation of the form
     * @param successCallback function the function to be invoked if the validation completes
     * @param errorCallback function the function to be invoked if the ajax validation request fails
     */
    var validate = function ($form, successCallback, errorCallback) {
        var data = $form.data('yiiActiveForm'),
            needAjaxValidation = false,
Alex-Code committed
392
            messages = {},
Alex-Code committed
393
            deferreds = deferredArray();
Qiang Xue committed
394

Qiang Xue committed
395 396 397
        $.each(data.attributes, function () {
            if (data.submitting || this.status === 2 || this.status === 3) {
                var msg = [];
Alex-Code committed
398
                messages[this.id] = msg;
Qiang Xue committed
399 400
                if (!data.settings.beforeValidate || data.settings.beforeValidate($form, this, msg)) {
                    if (this.validate) {
Alex-Code committed
401
                        this.validate(this, getValue($form, this), msg, deferreds);
Qiang Xue committed
402
                    }
Alex-Code committed
403
                    if (this.enableAjaxValidation) {
Qiang Xue committed
404 405 406 407 408
                        needAjaxValidation = true;
                    }
                }
            }
        });
Qiang Xue committed
409

Alex-Code committed
410
        $.when.apply(this, deferreds).always(function() {
Alex-Code committed
411 412 413 414 415 416
            //Remove empty message arrays
            for (var i in messages) {
                if (0 === messages[i].length) {
                    delete messages[i];
                }
            }
Alex-Code committed
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
            if (needAjaxValidation && (!data.submitting || $.isEmptyObject(messages))) {
                // Perform ajax validation when at least one input needs it.
                // If the validation is triggered by form submission, ajax validation
                // should be done only when all inputs pass client validation
                var $button = data.submitObject,
                    extData = '&' + data.settings.ajaxParam + '=' + $form.prop('id');
                if ($button && $button.length && $button.prop('name')) {
                    extData += '&' + $button.prop('name') + '=' + $button.prop('value');
                }
                $.ajax({
                    url: data.settings.validationUrl,
                    type: $form.prop('method'),
                    data: $form.serialize() + extData,
                    dataType: data.settings.ajaxDataType,
                    complete: function (jqXHR, textStatus) {
                        if (data.settings.ajaxComplete) {
                            data.settings.ajaxComplete($form, jqXHR, textStatus);
                        }
                    },
                    beforeSend: function (jqXHR, textStatus) {
                        if (data.settings.ajaxBeforeSend) {
                            data.settings.ajaxBeforeSend($form, jqXHR, textStatus);
                        }
                    },
                    success: function (msgs) {
                        if (msgs !== null && typeof msgs === 'object') {
                            $.each(data.attributes, function () {
                                if (!this.enableAjaxValidation) {
                                    delete msgs[this.id];
                                }
                            });
                            successCallback($.extend({}, messages, msgs));
                        } else {
                            successCallback(messages);
                        }
                    },
                    error: errorCallback
                });
            } else if (data.submitting) {
                // delay callback so that the form can be submitted without problem
                setTimeout(function () {
                    successCallback(messages);
                }, 200);
            } else {
Qiang Xue committed
461
                successCallback(messages);
Alex-Code committed
462 463
            }
        });
Qiang Xue committed
464
    };
Qiang Xue committed
465

Qiang Xue committed
466 467 468 469 470 471 472 473 474 475 476
    /**
     * Updates the error message and the input container for a particular attribute.
     * @param $form the form jQuery object
     * @param attribute object the configuration for a particular attribute.
     * @param messages array the validation error messages
     * @return boolean whether there is a validation error for the specified attribute
     */
    var updateInput = function ($form, attribute, messages) {
        var data = $form.data('yiiActiveForm'),
            $input = findInput($form, attribute),
            hasError = false;
Qiang Xue committed
477

Qiang Xue committed
478 479 480 481 482
        if (data.settings.afterValidate) {
            data.settings.afterValidate($form, attribute, messages);
        }
        attribute.status = 1;
        if ($input.length) {
483
            hasError = messages && $.isArray(messages[attribute.id]) && messages[attribute.id].length;
Qiang Xue committed
484 485 486
            var $container = $form.find(attribute.container);
            var $error = $container.find(attribute.error);
            if (hasError) {
487 488 489 490 491
                if (attribute.encodeError) {
                    $error.text(messages[attribute.id][0]);
                } else {
                    $error.html(messages[attribute.id][0]);
                }
Qiang Xue committed
492 493 494
                $container.removeClass(data.settings.validatingCssClass + ' ' + data.settings.successCssClass)
                    .addClass(data.settings.errorCssClass);
            } else {
495
                $error.empty();
Qiang Xue committed
496 497 498 499 500 501 502
                $container.removeClass(data.settings.validatingCssClass + ' ' + data.settings.errorCssClass + ' ')
                    .addClass(data.settings.successCssClass);
            }
            attribute.value = getValue($form, attribute);
        }
        return hasError;
    };
Qiang Xue committed
503

Qiang Xue committed
504 505 506 507 508 509 510 511
    /**
     * Updates the error summary.
     * @param $form the form jQuery object
     * @param messages array the validation error messages
     */
    var updateSummary = function ($form, messages) {
        var data = $form.data('yiiActiveForm'),
            $summary = $form.find(data.settings.errorSummary),
512
            $ul = $summary.find('ul').empty();
Qiang Xue committed
513

Qiang Xue committed
514 515
        if ($summary.length && messages) {
            $.each(data.attributes, function () {
516
                if ($.isArray(messages[this.id]) && messages[this.id].length) {
517 518 519 520 521 522 523
                    var error = $('<li/>');
                    if (data.settings.encodeErrorSummary) {
                        error.text(messages[this.id][0]);
                    } else {
                        error.html(messages[this.id][0]);
                    }
                    $ul.append(error);
Qiang Xue committed
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
                }
            });
            $summary.toggle($ul.find('li').length > 0);
        }
    };

    var getValue = function ($form, attribute) {
        var $input = findInput($form, attribute);
        var type = $input.prop('type');
        if (type === 'checkbox' || type === 'radio') {
            var $realInput = $input.filter(':checked');
            if (!$realInput.length) {
                $realInput = $form.find('input[type=hidden][name="' + $input.prop('name') + '"]');
            }
            return $realInput.val();
        } else {
            return $input.val();
        }
    };

    var findInput = function ($form, attribute) {
        var $input = $form.find(attribute.input);
        if ($input.length && $input[0].tagName.toLowerCase() === 'div') {
            // checkbox list or radio list
            return $input.find('input');
        } else {
            return $input;
        }
    };
Qiang Xue committed
553

554
})(window.jQuery);