Paul Klimov
7 years ago
33 changed files with 2 additions and 3876 deletions
@ -1,32 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery; |
||||
|
||||
use yii\web\AssetBundle; |
||||
|
||||
/** |
||||
* The asset bundle for the [[ActiveForm]] widget. |
||||
* |
||||
* @author Qiang Xue <qiang.xue@gmail.com> |
||||
* @since 2.0 |
||||
*/ |
||||
class ActiveFormAsset extends AssetBundle |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public $sourcePath = '@yii/jquery/assets'; |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public $js = ['yii.activeForm.js']; |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public $depends = [YiiAsset::class]; |
||||
} |
@ -1,115 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery; |
||||
|
||||
use Yii; |
||||
use yii\helpers\Json; |
||||
use yii\widgets\ActiveForm; |
||||
|
||||
/** |
||||
* ActiveFormClientScript is a behavior for [[\yii\widgets\ActiveForm]], which allows composition |
||||
* of the client-side and AJAX form validation via underlying JQuery plugin. |
||||
* |
||||
* Usage example: |
||||
* |
||||
* ```php |
||||
* <?php $form = \yii\widgets\ActiveForm::begin([ |
||||
* 'id' => 'example-form', |
||||
* 'as clientScript' => \yii\jquery\ActiveFormClientScript::class, |
||||
* // ... |
||||
* ]); ?> |
||||
* ... |
||||
* <?php \yii\widgets\ActiveForm::end(); ?> |
||||
* ``` |
||||
* |
||||
* @see \yii\widgets\ActiveForm |
||||
* @see \yii\widgets\ActiveFormClientScriptBehavior |
||||
* |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class ActiveFormClientScript extends \yii\widgets\ActiveFormClientScript |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
protected function defaultClientValidatorMap() |
||||
{ |
||||
return [ |
||||
\yii\validators\BooleanValidator::class => \yii\jquery\validators\client\BooleanValidator::class, |
||||
\yii\validators\CompareValidator::class => \yii\jquery\validators\client\CompareValidator::class, |
||||
\yii\validators\EmailValidator::class => \yii\jquery\validators\client\EmailValidator::class, |
||||
\yii\validators\FilterValidator::class => \yii\jquery\validators\client\FilterValidator::class, |
||||
\yii\validators\IpValidator::class => \yii\jquery\validators\client\IpValidator::class, |
||||
\yii\validators\NumberValidator::class => \yii\jquery\validators\client\NumberValidator::class, |
||||
\yii\validators\RangeValidator::class => \yii\jquery\validators\client\RangeValidator::class, |
||||
\yii\validators\RegularExpressionValidator::class => \yii\jquery\validators\client\RegularExpressionValidator::class, |
||||
\yii\validators\RequiredValidator::class => \yii\jquery\validators\client\RequiredValidator::class, |
||||
\yii\validators\StringValidator::class => \yii\jquery\validators\client\StringValidator::class, |
||||
\yii\validators\UrlValidator::class => \yii\jquery\validators\client\UrlValidator::class, |
||||
\yii\validators\ImageValidator::class => \yii\jquery\validators\client\ImageValidator::class, |
||||
\yii\validators\FileValidator::class => \yii\jquery\validators\client\FileValidator::class, |
||||
\yii\captcha\CaptchaValidator::class => \yii\jquery\validators\client\CaptchaClientValidator::class, |
||||
]; |
||||
} |
||||
|
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
protected function registerClientScript() |
||||
{ |
||||
$id = $this->owner->options['id']; |
||||
$options = Json::htmlEncode($this->getClientOptions()); |
||||
$attributes = Json::htmlEncode($this->attributes); |
||||
$view = $this->owner->getView(); |
||||
ActiveFormAsset::register($view); |
||||
$view->registerJs("jQuery('#$id').yiiActiveForm($attributes, $options);"); |
||||
} |
||||
|
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
protected function getFieldClientOptions($field) |
||||
{ |
||||
$options = parent::getFieldClientOptions($field); |
||||
|
||||
// only get the options that are different from the default ones (set in yii.activeForm.js) |
||||
return array_diff_assoc($options, [ |
||||
'validateOnChange' => true, |
||||
'validateOnBlur' => true, |
||||
'validateOnType' => false, |
||||
'validationDelay' => 500, |
||||
'encodeError' => true, |
||||
'error' => '.help-block', |
||||
'updateAriaInvalid' => true, |
||||
]); |
||||
} |
||||
|
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
protected function getClientOptions() |
||||
{ |
||||
$options = parent::getClientOptions(); |
||||
|
||||
// only get the options that are different from the default ones (set in yii.activeForm.js) |
||||
return array_diff_assoc($options, [ |
||||
'encodeErrorSummary' => true, |
||||
'errorSummary' => '.error-summary', |
||||
'validateOnSubmit' => true, |
||||
'errorCssClass' => 'has-error', |
||||
'successCssClass' => 'has-success', |
||||
'validatingCssClass' => 'validating', |
||||
'ajaxParam' => 'ajax', |
||||
'ajaxDataType' => 'json', |
||||
'scrollToError' => true, |
||||
'scrollToErrorOffset' => 0, |
||||
'validationStateOn' => ActiveForm::VALIDATION_STATE_ON_CONTAINER, |
||||
]); |
||||
} |
||||
} |
@ -1,32 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery; |
||||
|
||||
use yii\web\AssetBundle; |
||||
|
||||
/** |
||||
* This asset bundle provides the javascript files for the [[GridView]] widget. |
||||
* |
||||
* @author Qiang Xue <qiang.xue@gmail.com> |
||||
* @since 2.0 |
||||
*/ |
||||
class GridViewAsset extends AssetBundle |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public $sourcePath = '@yii/jquery/assets'; |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public $js = ['yii.gridView.js']; |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public $depends = [YiiAsset::class]; |
||||
} |
@ -1,94 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery; |
||||
|
||||
use Yii; |
||||
use yii\base\Behavior; |
||||
use yii\base\Widget; |
||||
use yii\helpers\Json; |
||||
use yii\helpers\Url; |
||||
|
||||
/** |
||||
* GridViewClientScript is a behavior for [[\yii\grid\GridView]] widget, which allows automatic filter submission via jQuery component. |
||||
* |
||||
* A basic usage looks like the following: |
||||
* |
||||
* ```php |
||||
* <?= yii\grid\GridView::widget([ |
||||
* 'dataProvider' => $dataProvider, |
||||
* 'as clientScript' => [ |
||||
* 'class' => yii\jquery\GridViewClientScript::class |
||||
* ], |
||||
* 'columns' => [ |
||||
* 'id', |
||||
* 'name', |
||||
* 'created_at:datetime', |
||||
* // ... |
||||
* ], |
||||
* ]) ?> |
||||
* ``` |
||||
* |
||||
* @see \yii\grid\GridView |
||||
* @see GridViewAsset |
||||
* |
||||
* @property \yii\grid\GridView $owner the owner of this behavior. |
||||
* |
||||
* @author Qiang Xue <qiang.xue@gmail.com> |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class GridViewClientScript extends Behavior |
||||
{ |
||||
/** |
||||
* @var string additional jQuery selector for selecting filter input fields. |
||||
*/ |
||||
public $filterSelector; |
||||
|
||||
|
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public function events() |
||||
{ |
||||
return [ |
||||
Widget::EVENT_BEFORE_RUN => 'beforeRun' |
||||
]; |
||||
} |
||||
|
||||
/** |
||||
* Handles [[Widget::EVENT_BEFORE_RUN]] event, registering related client script. |
||||
* @param \yii\base\Event $event event instance. |
||||
*/ |
||||
public function beforeRun($event) |
||||
{ |
||||
$id = $this->owner->options['id']; |
||||
$options = Json::htmlEncode($this->getClientOptions()); |
||||
$view = $this->owner->getView(); |
||||
GridViewAsset::register($view); |
||||
$view->registerJs("jQuery('#$id').yiiGridView($options);"); |
||||
} |
||||
|
||||
/** |
||||
* Returns the options for the grid view JS widget. |
||||
* @return array the options |
||||
*/ |
||||
protected function getClientOptions() |
||||
{ |
||||
$filterUrl = isset($this->owner->filterUrl) ? $this->owner->filterUrl : Yii::$app->request->url; |
||||
$id = $this->owner->filterRowOptions['id']; |
||||
$filterSelector = "#$id input, #$id select"; |
||||
if (isset($this->filterSelector)) { |
||||
$filterSelector .= ', ' . $this->filterSelector; |
||||
} |
||||
|
||||
return [ |
||||
'filterUrl' => Url::to($filterUrl), |
||||
'filterSelector' => $filterSelector, |
||||
]; |
||||
} |
||||
} |
@ -1,24 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery; |
||||
|
||||
use yii\web\AssetBundle; |
||||
|
||||
/** |
||||
* This asset bundle provides the [jQuery](http://jquery.com/) JavaScript library. |
||||
* |
||||
* @author Qiang Xue <qiang.xue@gmail.com> |
||||
* @since 2.0 |
||||
*/ |
||||
class JqueryAsset extends AssetBundle |
||||
{ |
||||
public $sourcePath = '@bower/jquery/dist'; |
||||
public $js = [ |
||||
'jquery.js', |
||||
]; |
||||
} |
@ -1,24 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery; |
||||
|
||||
use yii\web\AssetBundle; |
||||
|
||||
/** |
||||
* This asset bundle provides the javascript files needed for the [[EmailValidator]]s client validation. |
||||
* |
||||
* @author Qiang Xue <qiang.xue@gmail.com> |
||||
* @since 2.0 |
||||
*/ |
||||
class PunycodeAsset extends AssetBundle |
||||
{ |
||||
public $sourcePath = '@bower/punycode'; |
||||
public $js = [ |
||||
'punycode.js', |
||||
]; |
||||
} |
@ -1,32 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery; |
||||
|
||||
use yii\web\AssetBundle; |
||||
|
||||
/** |
||||
* This asset bundle provides the javascript files for client validation. |
||||
* |
||||
* @author Qiang Xue <qiang.xue@gmail.com> |
||||
* @since 2.0 |
||||
*/ |
||||
class ValidationAsset extends AssetBundle |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public $sourcePath = '@yii/jquery/assets'; |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public $js = ['yii.validation.js']; |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public $depends = [YiiAsset::class]; |
||||
} |
@ -1,32 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery; |
||||
|
||||
use yii\web\AssetBundle; |
||||
|
||||
/** |
||||
* This asset bundle provides the base JavaScript files for the Yii Framework. |
||||
* |
||||
* @author Qiang Xue <qiang.xue@gmail.com> |
||||
* @since 2.0 |
||||
*/ |
||||
class YiiAsset extends AssetBundle |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public $sourcePath = '@yii/jquery/assets'; |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public $js = ['yii.js']; |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public $depends = [JqueryAsset::class]; |
||||
} |
@ -1,799 +0,0 @@
|
||||
/** |
||||
* 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 ($) { |
||||
|
||||
$.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; |
||||
} |
||||
}; |
||||
|
||||
var events = { |
||||
/** |
||||
* beforeValidate event is triggered before validating the whole form. |
||||
* The signature of the event handler should be: |
||||
* function (event, messages, deferreds) |
||||
* where |
||||
* - event: an Event object. |
||||
* - messages: an associative array with keys being attribute IDs and values being error message arrays |
||||
* for the corresponding attributes. |
||||
* - deferreds: an array of Deferred objects. You can use deferreds.add(callback) to add a new deferred validation. |
||||
* |
||||
* If the handler returns a boolean false, it will stop further form validation after this event. And as |
||||
* a result, afterValidate event will not be triggered. |
||||
*/ |
||||
beforeValidate: 'beforeValidate', |
||||
/** |
||||
* afterValidate event is triggered after validating the whole form. |
||||
* The signature of the event handler should be: |
||||
* function (event, messages, errorAttributes) |
||||
* where |
||||
* - event: an Event object. |
||||
* - messages: an associative array with keys being attribute IDs and values being error message arrays |
||||
* for the corresponding attributes. |
||||
* - errorAttributes: an array of attributes that have validation errors. Please refer to attributeDefaults for the structure of this parameter. |
||||
*/ |
||||
afterValidate: 'afterValidate', |
||||
/** |
||||
* beforeValidateAttribute event is triggered before validating an attribute. |
||||
* The signature of the event handler should be: |
||||
* function (event, attribute, messages, deferreds) |
||||
* where |
||||
* - event: an Event object. |
||||
* - attribute: the attribute to be validated. Please refer to attributeDefaults for the structure of this parameter. |
||||
* - messages: an array to which you can add validation error messages for the specified attribute. |
||||
* - deferreds: an array of Deferred objects. You can use deferreds.add(callback) to add a new deferred validation. |
||||
* |
||||
* If the handler returns a boolean false, it will stop further validation of the specified attribute. |
||||
* And as a result, afterValidateAttribute event will not be triggered. |
||||
*/ |
||||
beforeValidateAttribute: 'beforeValidateAttribute', |
||||
/** |
||||
* afterValidateAttribute event is triggered after validating the whole form and each attribute. |
||||
* The signature of the event handler should be: |
||||
* function (event, attribute, messages) |
||||
* where |
||||
* - event: an Event object. |
||||
* - attribute: the attribute being validated. Please refer to attributeDefaults for the structure of this parameter. |
||||
* - messages: an array to which you can add additional validation error messages for the specified attribute. |
||||
*/ |
||||
afterValidateAttribute: 'afterValidateAttribute', |
||||
/** |
||||
* beforeSubmit event is triggered before submitting the form after all validations have passed. |
||||
* The signature of the event handler should be: |
||||
* function (event) |
||||
* where event is an Event object. |
||||
* |
||||
* If the handler returns a boolean false, it will stop form submission. |
||||
*/ |
||||
beforeSubmit: 'beforeSubmit', |
||||
/** |
||||
* ajaxBeforeSend event is triggered before sending an AJAX request for AJAX-based validation. |
||||
* The signature of the event handler should be: |
||||
* function (event, jqXHR, settings) |
||||
* where |
||||
* - event: an Event object. |
||||
* - jqXHR: a jqXHR object |
||||
* - settings: the settings for the AJAX request |
||||
*/ |
||||
ajaxBeforeSend: 'ajaxBeforeSend', |
||||
/** |
||||
* ajaxComplete event is triggered after completing an AJAX request for AJAX-based validation. |
||||
* The signature of the event handler should be: |
||||
* function (event, jqXHR, textStatus) |
||||
* where |
||||
* - event: an Event object. |
||||
* - jqXHR: a jqXHR object |
||||
* - textStatus: the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). |
||||
*/ |
||||
ajaxComplete: 'ajaxComplete', |
||||
/** |
||||
* afterInit event is triggered after yii activeForm init. |
||||
* The signature of the event handler should be: |
||||
* function (event) |
||||
* where |
||||
* - event: an Event object. |
||||
*/ |
||||
afterInit: 'afterInit' |
||||
}; |
||||
|
||||
// NOTE: If you change any of these defaults, make sure you update yii\widgets\ActiveForm::getClientOptions() as well
|
||||
var defaults = { |
||||
// whether to encode the error summary
|
||||
encodeErrorSummary: true, |
||||
// the jQuery selector for the error summary
|
||||
errorSummary: '.error-summary', |
||||
// whether to perform validation before submitting the form.
|
||||
validateOnSubmit: true, |
||||
// the container CSS class representing the corresponding attribute has validation error
|
||||
errorCssClass: 'has-error', |
||||
// the container CSS class representing the corresponding attribute passes validation
|
||||
successCssClass: 'has-success', |
||||
// the container CSS class representing the corresponding attribute is being validated
|
||||
validatingCssClass: 'validating', |
||||
// 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', |
||||
// the URL for performing AJAX-based validation. If not set, it will use the the form's action
|
||||
validationUrl: undefined, |
||||
// whether to scroll to first visible error after validation.
|
||||
scrollToError: true, |
||||
// offset in pixels that should be added when scrolling to the first error.
|
||||
scrollToErrorOffset: 0, |
||||
// where to add validation class: container or input
|
||||
validationStateOn: 'container' |
||||
}; |
||||
|
||||
// NOTE: If you change any of these defaults, make sure you update yii\widgets\ActiveField::getClientOptions() as well
|
||||
var attributeDefaults = { |
||||
// a unique ID identifying an attribute (e.g. "loginform-username") in a form
|
||||
id: undefined, |
||||
// 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, |
||||
// the jQuery selector of the input field under the context of the form
|
||||
input: undefined, |
||||
// the jQuery selector of the error tag under the context of the container
|
||||
error: '.help-block', |
||||
// whether to encode the error
|
||||
encodeError: true, |
||||
// whether to perform validation when a change is detected on the input
|
||||
validateOnChange: true, |
||||
// whether to perform validation when the input loses focus
|
||||
validateOnBlur: true, |
||||
// 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: 500, |
||||
// whether to enable AJAX-based validation.
|
||||
enableAjaxValidation: false, |
||||
// function (attribute, value, messages, deferred, $form), 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, |
||||
// whether the validation is cancelled by beforeValidateAttribute event handler
|
||||
cancelled: false, |
||||
// the value of the input
|
||||
value: undefined, |
||||
// whether to update aria-invalid attribute after validation
|
||||
updateAriaInvalid: true |
||||
}; |
||||
|
||||
|
||||
var submitDefer; |
||||
|
||||
var setSubmitFinalizeDefer = function($form) { |
||||
submitDefer = $.Deferred(); |
||||
$form.data('yiiSubmitFinalizePromise', submitDefer.promise()); |
||||
}; |
||||
|
||||
// finalize yii.js $form.submit
|
||||
var submitFinalize = function($form) { |
||||
if(submitDefer) { |
||||
submitDefer.resolve(); |
||||
submitDefer = undefined; |
||||
$form.removeData('yiiSubmitFinalizePromise'); |
||||
} |
||||
}; |
||||
|
||||
|
||||
var methods = { |
||||
init: function (attributes, options) { |
||||
return this.each(function () { |
||||
var $form = $(this); |
||||
if ($form.data('yiiActiveForm')) { |
||||
return; |
||||
} |
||||
|
||||
var settings = $.extend({}, defaults, options || {}); |
||||
if (settings.validationUrl === undefined) { |
||||
settings.validationUrl = $form.attr('action'); |
||||
} |
||||
|
||||
$.each(attributes, function (i) { |
||||
attributes[i] = $.extend({value: getValue($form, this)}, attributeDefaults, this); |
||||
watchAttribute($form, attributes[i]); |
||||
}); |
||||
|
||||
$form.data('yiiActiveForm', { |
||||
settings: settings, |
||||
attributes: attributes, |
||||
submitting: false, |
||||
validated: false, |
||||
options: getFormOptions($form) |
||||
}); |
||||
|
||||
/** |
||||
* 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.on('reset.yiiActiveForm', methods.resetForm); |
||||
|
||||
if (settings.validateOnSubmit) { |
||||
$form.on('mouseup.yiiActiveForm keyup.yiiActiveForm', ':submit', function () { |
||||
$form.data('yiiActiveForm').submitObject = $(this); |
||||
}); |
||||
$form.on('submit.yiiActiveForm', methods.submitForm); |
||||
} |
||||
var event = $.Event(events.afterInit); |
||||
$form.trigger(event); |
||||
}); |
||||
}, |
||||
|
||||
// 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 = undefined; |
||||
$.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; |
||||
}, |
||||
|
||||
// manually trigger the validation of the attribute with the specified ID
|
||||
validateAttribute: function (id) { |
||||
var attribute = methods.find.call(this, id); |
||||
if (attribute != undefined) { |
||||
validateAttribute($(this), attribute, true); |
||||
} |
||||
}, |
||||
|
||||
// find an attribute config based on the specified attribute ID
|
||||
find: function (id) { |
||||
var attributes = $(this).data('yiiActiveForm').attributes, |
||||
result = undefined; |
||||
$.each(attributes, function (i) { |
||||
if (attributes[i]['id'] == id) { |
||||
result = attributes[i]; |
||||
return false; |
||||
} |
||||
}); |
||||
return result; |
||||
}, |
||||
|
||||
destroy: function () { |
||||
return this.each(function () { |
||||
$(this).off('.yiiActiveForm'); |
||||
$(this).removeData('yiiActiveForm'); |
||||
}); |
||||
}, |
||||
|
||||
data: function () { |
||||
return this.data('yiiActiveForm'); |
||||
}, |
||||
|
||||
// validate all applicable inputs in the form
|
||||
validate: function (forceValidate) { |
||||
if (forceValidate) { |
||||
$(this).data('yiiActiveForm').submitting = true; |
||||
} |
||||
|
||||
var $form = $(this), |
||||
data = $form.data('yiiActiveForm'), |
||||
needAjaxValidation = false, |
||||
messages = {}, |
||||
deferreds = deferredArray(), |
||||
submitting = data.submitting; |
||||
|
||||
if (submitting) { |
||||
var event = $.Event(events.beforeValidate); |
||||
$form.trigger(event, [messages, deferreds]); |
||||
|
||||
if (event.result === false) { |
||||
data.submitting = false; |
||||
submitFinalize($form); |
||||
return; |
||||
} |
||||
} |
||||
|
||||
// client-side validation
|
||||
$.each(data.attributes, function () { |
||||
this.$form = $form; |
||||
if (!$(this.input).is(":disabled")) { |
||||
this.cancelled = false; |
||||
// perform validation only if the form is being submitted or if an attribute is pending validation
|
||||
if (data.submitting || this.status === 2 || this.status === 3) { |
||||
var msg = messages[this.id]; |
||||
if (msg === undefined) { |
||||
msg = []; |
||||
messages[this.id] = msg; |
||||
} |
||||
var event = $.Event(events.beforeValidateAttribute); |
||||
$form.trigger(event, [this, msg, deferreds]); |
||||
if (event.result !== false) { |
||||
if (this.validate) { |
||||
this.validate(this, getValue($form, this), msg, deferreds, $form); |
||||
} |
||||
if (this.enableAjaxValidation) { |
||||
needAjaxValidation = true; |
||||
} |
||||
} else { |
||||
this.cancelled = true; |
||||
} |
||||
} |
||||
} |
||||
}); |
||||
|
||||
// ajax validation
|
||||
$.when.apply(this, deferreds).always(function() { |
||||
// Remove empty message arrays
|
||||
for (var i in messages) { |
||||
if (0 === messages[i].length) { |
||||
delete messages[i]; |
||||
} |
||||
} |
||||
if (needAjaxValidation && ($.isEmptyObject(messages) || data.submitting)) { |
||||
var $button = data.submitObject, |
||||
extData = '&' + data.settings.ajaxParam + '=' + $form.attr('id'); |
||||
if ($button && $button.length && $button.attr('name')) { |
||||
extData += '&' + $button.attr('name') + '=' + $button.attr('value'); |
||||
} |
||||
$.ajax({ |
||||
url: data.settings.validationUrl, |
||||
type: $form.attr('method'), |
||||
data: $form.serialize() + extData, |
||||
dataType: data.settings.ajaxDataType, |
||||
complete: function (jqXHR, textStatus) { |
||||
$form.trigger(events.ajaxComplete, [jqXHR, textStatus]); |
||||
}, |
||||
beforeSend: function (jqXHR, settings) { |
||||
$form.trigger(events.ajaxBeforeSend, [jqXHR, settings]); |
||||
}, |
||||
success: function (msgs) { |
||||
if (msgs !== null && typeof msgs === 'object') { |
||||
$.each(data.attributes, function () { |
||||
if (!this.enableAjaxValidation || this.cancelled) { |
||||
delete msgs[this.id]; |
||||
} |
||||
}); |
||||
updateInputs($form, $.extend(messages, msgs), submitting); |
||||
} else { |
||||
updateInputs($form, messages, submitting); |
||||
} |
||||
}, |
||||
error: function () { |
||||
data.submitting = false; |
||||
submitFinalize($form); |
||||
} |
||||
}); |
||||
} else if (data.submitting) { |
||||
// delay callback so that the form can be submitted without problem
|
||||
window.setTimeout(function () { |
||||
updateInputs($form, messages, submitting); |
||||
}, 200); |
||||
} else { |
||||
updateInputs($form, messages, submitting); |
||||
} |
||||
}); |
||||
}, |
||||
|
||||
submitForm: function () { |
||||
var $form = $(this), |
||||
data = $form.data('yiiActiveForm'); |
||||
|
||||
if (data.validated) { |
||||
// Second submit's call (from validate/updateInputs)
|
||||
data.submitting = false; |
||||
var event = $.Event(events.beforeSubmit); |
||||
$form.trigger(event); |
||||
if (event.result === false) { |
||||
data.validated = false; |
||||
submitFinalize($form); |
||||
return false; |
||||
} |
||||
updateHiddenButton($form); |
||||
return true; // continue submitting the form since validation passes
|
||||
} else { |
||||
// First submit's call (from yii.js/handleAction) - execute validating
|
||||
setSubmitFinalizeDefer($form); |
||||
|
||||
if (data.settings.timer !== undefined) { |
||||
clearTimeout(data.settings.timer); |
||||
} |
||||
data.submitting = true; |
||||
methods.validate.call($form); |
||||
return false; |
||||
} |
||||
}, |
||||
|
||||
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.
|
||||
window.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), |
||||
$input = findInput($form, this), |
||||
$errorElement = data.settings.validationStateOn === 'input' ? $input : $container; |
||||
|
||||
$errorElement.removeClass( |
||||
data.settings.validatingCssClass + ' ' + |
||||
data.settings.errorCssClass + ' ' + |
||||
data.settings.successCssClass |
||||
); |
||||
$container.find(this.error).html(''); |
||||
}); |
||||
$form.find(data.settings.errorSummary).hide().find('ul').html(''); |
||||
}, 1); |
||||
}, |
||||
|
||||
/** |
||||
* Updates error messages, input containers, and optionally summary as well. |
||||
* If an attribute is missing from messages, it is considered valid. |
||||
* @param messages array the validation error messages, indexed by attribute IDs |
||||
* @param summary whether to update summary as well. |
||||
*/ |
||||
updateMessages: function (messages, summary) { |
||||
var $form = $(this); |
||||
var data = $form.data('yiiActiveForm'); |
||||
$.each(data.attributes, function () { |
||||
updateInput($form, this, messages); |
||||
}); |
||||
if (summary) { |
||||
updateSummary($form, messages); |
||||
} |
||||
}, |
||||
|
||||
/** |
||||
* Updates error messages and input container of a single attribute. |
||||
* If messages is empty, the attribute is considered valid. |
||||
* @param id attribute ID |
||||
* @param messages array with error messages |
||||
*/ |
||||
updateAttribute: function(id, messages) { |
||||
var attribute = methods.find.call(this, id); |
||||
if (attribute != undefined) { |
||||
var msg = {}; |
||||
msg[id] = messages; |
||||
updateInput($(this), attribute, msg); |
||||
} |
||||
} |
||||
|
||||
}; |
||||
|
||||
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, true); |
||||
} |
||||
}); |
||||
} |
||||
if (attribute.validateOnType) { |
||||
$input.on('keyup.yiiActiveForm', function (e) { |
||||
if ($.inArray(e.which, [16, 17, 18, 37, 38, 39, 40]) !== -1 ) { |
||||
return; |
||||
} |
||||
if (attribute.value !== getValue($form, attribute)) { |
||||
validateAttribute($form, attribute, false, attribute.validationDelay); |
||||
} |
||||
}); |
||||
} |
||||
}; |
||||
|
||||
var unwatchAttribute = function ($form, attribute) { |
||||
findInput($form, attribute).off('.yiiActiveForm'); |
||||
}; |
||||
|
||||
var validateAttribute = function ($form, attribute, forceValidate, validationDelay) { |
||||
var data = $form.data('yiiActiveForm'); |
||||
|
||||
if (forceValidate) { |
||||
attribute.status = 2; |
||||
} |
||||
$.each(data.attributes, function () { |
||||
if (this.value !== getValue($form, this)) { |
||||
this.status = 2; |
||||
forceValidate = true; |
||||
} |
||||
}); |
||||
if (!forceValidate) { |
||||
return; |
||||
} |
||||
|
||||
if (data.settings.timer !== undefined) { |
||||
clearTimeout(data.settings.timer); |
||||
} |
||||
data.settings.timer = window.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); |
||||
} |
||||
}); |
||||
methods.validate.call($form); |
||||
}, validationDelay ? validationDelay : 200); |
||||
}; |
||||
|
||||
/** |
||||
* 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) { |
||||
this.push(new $.Deferred(callback)); |
||||
}; |
||||
return array; |
||||
}; |
||||
|
||||
var buttonOptions = ['action', 'target', 'method', 'enctype']; |
||||
|
||||
/** |
||||
* Returns current form options |
||||
* @param $form |
||||
* @returns object Object with button of form options |
||||
*/ |
||||
var getFormOptions = function ($form) { |
||||
var attributes = {}; |
||||
for (var i = 0; i < buttonOptions.length; i++) { |
||||
attributes[buttonOptions[i]] = $form.attr(buttonOptions[i]); |
||||
} |
||||
|
||||
return attributes; |
||||
}; |
||||
|
||||
/** |
||||
* Applies temporary form options related to submit button |
||||
* @param $form the form jQuery object |
||||
* @param $button the button jQuery object |
||||
*/ |
||||
var applyButtonOptions = function ($form, $button) { |
||||
for (var i = 0; i < buttonOptions.length; i++) { |
||||
var value = $button.attr('form' + buttonOptions[i]); |
||||
if (value) { |
||||
$form.attr(buttonOptions[i], value); |
||||
} |
||||
} |
||||
}; |
||||
|
||||
/** |
||||
* Restores original form options |
||||
* @param $form the form jQuery object |
||||
*/ |
||||
var restoreButtonOptions = function ($form) { |
||||
var data = $form.data('yiiActiveForm'); |
||||
|
||||
for (var i = 0; i < buttonOptions.length; i++) { |
||||
$form.attr(buttonOptions[i], data.options[buttonOptions[i]] || null); |
||||
} |
||||
}; |
||||
|
||||
/** |
||||
* Updates the error messages and the input containers for all applicable attributes |
||||
* @param $form the form jQuery object |
||||
* @param messages array the validation error messages |
||||
* @param submitting whether this method is called after validation triggered by form submission |
||||
*/ |
||||
var updateInputs = function ($form, messages, submitting) { |
||||
var data = $form.data('yiiActiveForm'); |
||||
|
||||
if (data === undefined) { |
||||
return false; |
||||
} |
||||
|
||||
if (submitting) { |
||||
var errorAttributes = []; |
||||
$.each(data.attributes, function () { |
||||
if (!$(this.input).is(":disabled") && !this.cancelled && updateInput($form, this, messages)) { |
||||
errorAttributes.push(this); |
||||
} |
||||
}); |
||||
|
||||
$form.trigger(events.afterValidate, [messages, errorAttributes]); |
||||
|
||||
updateSummary($form, messages); |
||||
|
||||
if (errorAttributes.length) { |
||||
if (data.settings.scrollToError) { |
||||
var top = $form.find($.map(errorAttributes, function(attribute) { |
||||
return attribute.input; |
||||
}).join(',')).first().closest(':visible').offset().top - data.settings.scrollToErrorOffset; |
||||
if (top < 0) { |
||||
top = 0; |
||||
} else if (top > $(document).height()) { |
||||
top = $(document).height(); |
||||
} |
||||
var wtop = $(window).scrollTop(); |
||||
if (top < wtop || top > wtop + $(window).height()) { |
||||
$(window).scrollTop(top); |
||||
} |
||||
} |
||||
data.submitting = false; |
||||
} else { |
||||
data.validated = true; |
||||
if (data.submitObject) { |
||||
applyButtonOptions($form, data.submitObject); |
||||
} |
||||
$form.submit(); |
||||
if (data.submitObject) { |
||||
restoreButtonOptions($form); |
||||
} |
||||
} |
||||
} else { |
||||
$.each(data.attributes, function () { |
||||
if (!this.cancelled && (this.status === 2 || this.status === 3)) { |
||||
updateInput($form, this, messages); |
||||
} |
||||
}); |
||||
} |
||||
submitFinalize($form); |
||||
}; |
||||
|
||||
/** |
||||
* Updates hidden field that represents clicked submit button. |
||||
* @param $form the form jQuery object. |
||||
*/ |
||||
var updateHiddenButton = function ($form) { |
||||
var data = $form.data('yiiActiveForm'); |
||||
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.attr('type') == 'submit' && $button.attr('name')) { |
||||
// simulate button input value
|
||||
var $hiddenButton = $('input[type="hidden"][name="' + $button.attr('name') + '"]', $form); |
||||
if (!$hiddenButton.length) { |
||||
$('<input>').attr({ |
||||
type: 'hidden', |
||||
name: $button.attr('name'), |
||||
value: $button.attr('value') |
||||
}).appendTo($form); |
||||
} else { |
||||
$hiddenButton.attr('value', $button.attr('value')); |
||||
} |
||||
} |
||||
}; |
||||
|
||||
/** |
||||
* 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; |
||||
|
||||
if (!$.isArray(messages[attribute.id])) { |
||||
messages[attribute.id] = []; |
||||
} |
||||
|
||||
attribute.status = 1; |
||||
if ($input.length) { |
||||
hasError = messages[attribute.id].length > 0; |
||||
var $container = $form.find(attribute.container); |
||||
var $error = $container.find(attribute.error); |
||||
updateAriaInvalid($form, attribute, hasError); |
||||
|
||||
var $errorElement = data.settings.validationStateOn === 'input' ? $input : $container; |
||||
|
||||
if (hasError) { |
||||
if (attribute.encodeError) { |
||||
$error.text(messages[attribute.id][0]); |
||||
} else { |
||||
$error.html(messages[attribute.id][0]); |
||||
} |
||||
$errorElement.removeClass(data.settings.validatingCssClass + ' ' + data.settings.successCssClass) |
||||
.addClass(data.settings.errorCssClass); |
||||
} else { |
||||
$error.empty(); |
||||
$errorElement.removeClass(data.settings.validatingCssClass + ' ' + data.settings.errorCssClass + ' ') |
||||
.addClass(data.settings.successCssClass); |
||||
} |
||||
attribute.value = getValue($form, attribute); |
||||
} |
||||
|
||||
$form.trigger(events.afterValidateAttribute, [attribute, messages[attribute.id]]); |
||||
|
||||
return hasError; |
||||
}; |
||||
|
||||
/** |
||||
* 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), |
||||
$ul = $summary.find('ul').empty(); |
||||
|
||||
if ($summary.length && messages) { |
||||
$.each(data.attributes, function () { |
||||
if ($.isArray(messages[this.id]) && messages[this.id].length) { |
||||
var error = $('<li/>'); |
||||
if (data.settings.encodeErrorSummary) { |
||||
error.text(messages[this.id][0]); |
||||
} else { |
||||
error.html(messages[this.id][0]); |
||||
} |
||||
$ul.append(error); |
||||
} |
||||
}); |
||||
$summary.toggle($ul.find('li').length > 0); |
||||
} |
||||
}; |
||||
|
||||
var getValue = function ($form, attribute) { |
||||
var $input = findInput($form, attribute); |
||||
var type = $input.attr('type'); |
||||
if (type === 'checkbox' || type === 'radio') { |
||||
var $realInput = $input.filter(':checked'); |
||||
if (!$realInput.length) { |
||||
$realInput = $form.find('input[type=hidden][name="' + $input.attr('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; |
||||
} |
||||
}; |
||||
|
||||
var updateAriaInvalid = function ($form, attribute, hasError) { |
||||
if (attribute.updateAriaInvalid) { |
||||
$form.find(attribute.input).attr('aria-invalid', hasError ? 'true' : 'false'); |
||||
} |
||||
} |
||||
})(window.jQuery); |
@ -1,254 +0,0 @@
|
||||
/** |
||||
* Yii GridView widget. |
||||
* |
||||
* This is the JavaScript widget used by the yii\grid\GridView 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 ($) { |
||||
$.fn.yiiGridView = 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 in jQuery.yiiGridView'); |
||||
return false; |
||||
} |
||||
}; |
||||
|
||||
var defaults = { |
||||
filterUrl: undefined, |
||||
filterSelector: undefined |
||||
}; |
||||
|
||||
var gridData = {}; |
||||
|
||||
var gridEvents = { |
||||
/** |
||||
* beforeFilter event is triggered before filtering the grid. |
||||
* The signature of the event handler should be: |
||||
* function (event) |
||||
* where |
||||
* - event: an Event object. |
||||
* |
||||
* If the handler returns a boolean false, it will stop filter form submission after this event. As |
||||
* a result, afterFilter event will not be triggered. |
||||
*/ |
||||
beforeFilter: 'beforeFilter', |
||||
/** |
||||
* afterFilter event is triggered after filtering the grid and filtered results are fetched. |
||||
* The signature of the event handler should be: |
||||
* function (event) |
||||
* where |
||||
* - event: an Event object. |
||||
*/ |
||||
afterFilter: 'afterFilter' |
||||
}; |
||||
|
||||
/** |
||||
* Used for storing active event handlers and removing them later. |
||||
* The structure of single event handler is: |
||||
* |
||||
* { |
||||
* gridViewId: { |
||||
* type: { |
||||
* event: '...', |
||||
* selector: '...' |
||||
* } |
||||
* } |
||||
* } |
||||
* |
||||
* Used types: |
||||
* |
||||
* - filter, used for filtering grid with elements found by filterSelector |
||||
* - checkRow, used for checking single row |
||||
* - checkAllRows, used for checking all rows with according "Check all" checkbox |
||||
* |
||||
* event is the name of event, for example: 'change.yiiGridView' |
||||
* selector is a jQuery selector for finding elements |
||||
* |
||||
* @type {{}} |
||||
*/ |
||||
var gridEventHandlers = {}; |
||||
|
||||
var methods = { |
||||
init: function (options) { |
||||
return this.each(function () { |
||||
var $e = $(this); |
||||
var settings = $.extend({}, defaults, options || {}); |
||||
var id = $e.attr('id'); |
||||
if (gridData[id] === undefined) { |
||||
gridData[id] = {}; |
||||
} |
||||
|
||||
gridData[id] = $.extend(gridData[id], {settings: settings}); |
||||
|
||||
var filterEvents = 'change.yiiGridView keydown.yiiGridView'; |
||||
var enterPressed = false; |
||||
initEventHandler($e, 'filter', filterEvents, settings.filterSelector, function (event) { |
||||
if (event.type === 'keydown') { |
||||
if (event.keyCode !== 13) { |
||||
return; // only react to enter key
|
||||
} else { |
||||
enterPressed = true; |
||||
} |
||||
} else { |
||||
// prevent processing for both keydown and change events
|
||||
if (enterPressed) { |
||||
enterPressed = false; |
||||
return; |
||||
} |
||||
} |
||||
|
||||
methods.applyFilter.apply($e); |
||||
|
||||
return false; |
||||
}); |
||||
}); |
||||
}, |
||||
|
||||
applyFilter: function () { |
||||
var $grid = $(this); |
||||
var settings = gridData[$grid.attr('id')].settings; |
||||
var data = {}; |
||||
$.each($(settings.filterSelector).serializeArray(), function () { |
||||
if (!(this.name in data)) { |
||||
data[this.name] = []; |
||||
} |
||||
data[this.name].push(this.value); |
||||
}); |
||||
|
||||
var namesInFilter = Object.keys(data); |
||||
|
||||
$.each(yii.getQueryParams(settings.filterUrl), function (name, value) { |
||||
if (namesInFilter.indexOf(name) === -1 && namesInFilter.indexOf(name.replace(/\[\d*\]$/, '')) === -1) { |
||||
if (!$.isArray(value)) { |
||||
value = [value]; |
||||
} |
||||
if (!(name in data)) { |
||||
data[name] = value; |
||||
} else { |
||||
$.each(value, function (i, val) { |
||||
if ($.inArray(val, data[name])) { |
||||
data[name].push(val); |
||||
} |
||||
}); |
||||
} |
||||
} |
||||
}); |
||||
|
||||
var pos = settings.filterUrl.indexOf('?'); |
||||
var url = pos < 0 ? settings.filterUrl : settings.filterUrl.substring(0, pos); |
||||
var hashPos = settings.filterUrl.indexOf('#'); |
||||
if (pos >= 0 && hashPos >= 0) { |
||||
url += settings.filterUrl.substring(hashPos); |
||||
} |
||||
|
||||
$grid.find('form.gridview-filter-form').remove(); |
||||
var $form = $('<form/>', { |
||||
action: url, |
||||
method: 'get', |
||||
'class': 'gridview-filter-form', |
||||
style: 'display:none', |
||||
'data-pjax': '' |
||||
}).appendTo($grid); |
||||
$.each(data, function (name, values) { |
||||
$.each(values, function (index, value) { |
||||
$form.append($('<input/>').attr({type: 'hidden', name: name, value: value})); |
||||
}); |
||||
}); |
||||
|
||||
var event = $.Event(gridEvents.beforeFilter); |
||||
$grid.trigger(event); |
||||
if (event.result === false) { |
||||
return; |
||||
} |
||||
|
||||
$form.submit(); |
||||
|
||||
$grid.trigger(gridEvents.afterFilter); |
||||
}, |
||||
|
||||
setSelectionColumn: function (options) { |
||||
var $grid = $(this); |
||||
var id = $(this).attr('id'); |
||||
if (gridData[id] === undefined) { |
||||
gridData[id] = {}; |
||||
} |
||||
gridData[id].selectionColumn = options.name; |
||||
if (!options.multiple || !options.checkAll) { |
||||
return; |
||||
} |
||||
var checkAll = "#" + id + " input[name='" + options.checkAll + "']"; |
||||
var inputs = options['class'] ? "input." + options['class'] : "input[name='" + options.name + "']"; |
||||
var inputsEnabled = "#" + id + " " + inputs + ":enabled"; |
||||
initEventHandler($grid, 'checkAllRows', 'click.yiiGridView', checkAll, function () { |
||||
$grid.find(inputs + ":enabled").prop('checked', this.checked); |
||||
}); |
||||
initEventHandler($grid, 'checkRow', 'click.yiiGridView', inputsEnabled, function () { |
||||
var all = $grid.find(inputs).length == $grid.find(inputs + ":checked").length; |
||||
$grid.find("input[name='" + options.checkAll + "']").prop('checked', all); |
||||
}); |
||||
}, |
||||
|
||||
getSelectedRows: function () { |
||||
var $grid = $(this); |
||||
var data = gridData[$grid.attr('id')]; |
||||
var keys = []; |
||||
if (data.selectionColumn) { |
||||
$grid.find("input[name='" + data.selectionColumn + "']:checked").each(function () { |
||||
keys.push($(this).parent().closest('tr').data('key')); |
||||
}); |
||||
} |
||||
|
||||
return keys; |
||||
}, |
||||
|
||||
destroy: function () { |
||||
var events = ['.yiiGridView', gridEvents.beforeFilter, gridEvents.afterFilter].join(' '); |
||||
this.off(events); |
||||
|
||||
var id = $(this).attr('id'); |
||||
$.each(gridEventHandlers[id], function (type, data) { |
||||
$(document).off(data.event, data.selector); |
||||
}); |
||||
|
||||
delete gridData[id]; |
||||
|
||||
return this; |
||||
}, |
||||
|
||||
data: function () { |
||||
var id = $(this).attr('id'); |
||||
return gridData[id]; |
||||
} |
||||
}; |
||||
|
||||
/** |
||||
* Used for attaching event handler and prevent of duplicating them. With each call previously attached handler of |
||||
* the same type is removed even selector was changed. |
||||
* @param {jQuery} $gridView According jQuery grid view element |
||||
* @param {string} type Type of the event which acts like a key |
||||
* @param {string} event Event name, for example 'change.yiiGridView' |
||||
* @param {string} selector jQuery selector |
||||
* @param {function} callback The actual function to be executed with this event |
||||
*/ |
||||
function initEventHandler($gridView, type, event, selector, callback) { |
||||
var id = $gridView.attr('id'); |
||||
var prevHandler = gridEventHandlers[id]; |
||||
if (prevHandler !== undefined && prevHandler[type] !== undefined) { |
||||
var data = prevHandler[type]; |
||||
$(document).off(data.event, data.selector); |
||||
} |
||||
if (prevHandler === undefined) { |
||||
gridEventHandlers[id] = {}; |
||||
} |
||||
$(document).on(event, selector, callback); |
||||
gridEventHandlers[id][type] = {event: event, selector: selector}; |
||||
} |
||||
})(window.jQuery); |
@ -1,522 +0,0 @@
|
||||
/** |
||||
* Yii JavaScript module. |
||||
* |
||||
* @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 |
||||
*/ |
||||
|
||||
/** |
||||
* yii is the root module for all Yii JavaScript modules. |
||||
* It implements a mechanism of organizing JavaScript code in modules through the function "yii.initModule()". |
||||
* |
||||
* Each module should be named as "x.y.z", where "x" stands for the root module (for the Yii core code, this is "yii"). |
||||
* |
||||
* A module may be structured as follows: |
||||
* |
||||
* ```javascript
|
||||
* window.yii.sample = (function($) { |
||||
* var pub = { |
||||
* // whether this module is currently active. If false, init() will not be called for this module
|
||||
* // it will also not be called for all its child modules. If this property is undefined, it means true.
|
||||
* isActive: true, |
||||
* init: function() { |
||||
* // ... module initialization code goes here ...
|
||||
* }, |
||||
* |
||||
* // ... other public functions and properties go here ...
|
||||
* }; |
||||
* |
||||
* // ... private functions and properties go here ...
|
||||
* |
||||
* return pub; |
||||
* })(window.jQuery); |
||||
* ``` |
||||
* |
||||
* Using this structure, you can define public and private functions/properties for a module. |
||||
* Private functions/properties are only visible within the module, while public functions/properties |
||||
* may be accessed outside of the module. For example, you can access "yii.sample.isActive". |
||||
* |
||||
* You must call "yii.initModule()" once for the root module of all your modules. |
||||
*/ |
||||
window.yii = (function ($) { |
||||
var pub = { |
||||
/** |
||||
* List of JS or CSS URLs that can be loaded multiple times via AJAX requests. |
||||
* Each item may be represented as either an absolute URL or a relative one. |
||||
* Each item may contain a wildcard matching character `*`, that means one or more |
||||
* any characters on the position. For example: |
||||
* - `/css/*.css` will match any file ending with `.css` in the `css` directory of the current web site |
||||
* - `http*://cdn.example.com/*` will match any files on domain `cdn.example.com`, loaded with HTTP or HTTPS |
||||
* - `/js/myCustomScript.js?realm=*` will match file `/js/myCustomScript.js` with defined `realm` parameter |
||||
*/ |
||||
reloadableScripts: [], |
||||
/** |
||||
* The selector for clickable elements that need to support confirmation and form submission. |
||||
*/ |
||||
clickableSelector: 'a, button, input[type="submit"], input[type="button"], input[type="reset"], ' + |
||||
'input[type="image"]', |
||||
/** |
||||
* The selector for changeable elements that need to support confirmation and form submission. |
||||
*/ |
||||
changeableSelector: 'select, input, textarea', |
||||
|
||||
/** |
||||
* @return string|undefined the CSRF parameter name. Undefined is returned if CSRF validation is not enabled. |
||||
*/ |
||||
getCsrfParam: function () { |
||||
return $('meta[name=csrf-param]').attr('content'); |
||||
}, |
||||
|
||||
/** |
||||
* @return string|undefined the CSRF token. Undefined is returned if CSRF validation is not enabled. |
||||
*/ |
||||
getCsrfToken: function () { |
||||
return $('meta[name=csrf-token]').attr('content'); |
||||
}, |
||||
|
||||
/** |
||||
* Sets the CSRF token in the meta elements. |
||||
* This method is provided so that you can update the CSRF token with the latest one you obtain from the server. |
||||
* @param name the CSRF token name |
||||
* @param value the CSRF token value |
||||
*/ |
||||
setCsrfToken: function (name, value) { |
||||
$('meta[name=csrf-param]').attr('content', name); |
||||
$('meta[name=csrf-token]').attr('content', value); |
||||
}, |
||||
|
||||
/** |
||||
* Updates all form CSRF input fields with the latest CSRF token. |
||||
* This method is provided to avoid cached forms containing outdated CSRF tokens. |
||||
*/ |
||||
refreshCsrfToken: function () { |
||||
var token = pub.getCsrfToken(); |
||||
if (token) { |
||||
$('form input[name="' + pub.getCsrfParam() + '"]').val(token); |
||||
} |
||||
}, |
||||
|
||||
/** |
||||
* Displays a confirmation dialog. |
||||
* The default implementation simply displays a js confirmation dialog. |
||||
* You may override this by setting `yii.confirm`. |
||||
* @param message the confirmation message. |
||||
* @param ok a callback to be called when the user confirms the message |
||||
* @param cancel a callback to be called when the user cancels the confirmation |
||||
*/ |
||||
confirm: function (message, ok, cancel) { |
||||
if (window.confirm(message)) { |
||||
!ok || ok(); |
||||
} else { |
||||
!cancel || cancel(); |
||||
} |
||||
}, |
||||
|
||||
/** |
||||
* Handles the action triggered by user. |
||||
* This method recognizes the `data-method` attribute of the element. If the attribute exists, |
||||
* the method will submit the form containing this element. If there is no containing form, a form |
||||
* will be created and submitted using the method given by this attribute value (e.g. "post", "put"). |
||||
* For hyperlinks, the form action will take the value of the "href" attribute of the link. |
||||
* For other elements, either the containing form action or the current page URL will be used |
||||
* as the form action URL. |
||||
* |
||||
* If the `data-method` attribute is not defined, the `href` attribute (if any) of the element |
||||
* will be assigned to `window.location`. |
||||
* |
||||
* Starting from version 2.0.3, the `data-params` attribute is also recognized when you specify |
||||
* `data-method`. The value of `data-params` should be a JSON representation of the data (name-value pairs) |
||||
* that should be submitted as hidden inputs. For example, you may use the following code to generate |
||||
* such a link: |
||||
* |
||||
* ```php
|
||||
* use yii\helpers\Html; |
||||
* use yii\helpers\Json; |
||||
* |
||||
* echo Html::a('submit', ['site/foobar'], [ |
||||
* 'data' => [ |
||||
* 'method' => 'post', |
||||
* 'params' => [ |
||||
* 'name1' => 'value1', |
||||
* 'name2' => 'value2', |
||||
* ], |
||||
* ], |
||||
* ]); |
||||
* ``` |
||||
* |
||||
* @param $e the jQuery representation of the element |
||||
* @param event Related event |
||||
*/ |
||||
handleAction: function ($e, event) { |
||||
var $form = $e.attr('data-form') ? $('#' + $e.attr('data-form')) : $e.closest('form'), |
||||
method = !$e.data('method') && $form ? $form.attr('method') : $e.data('method'), |
||||
action = $e.attr('href'), |
||||
isValidAction = action && action !== '#', |
||||
params = $e.data('params'), |
||||
areValidParams = params && $.isPlainObject(params), |
||||
pjax = $e.data('pjax'), |
||||
usePjax = pjax !== undefined && pjax !== 0 && $.support.pjax, |
||||
pjaxContainer, |
||||
pjaxOptions = {}; |
||||
|
||||
if (usePjax) { |
||||
pjaxContainer = $e.data('pjax-container'); |
||||
if (pjaxContainer === undefined || !pjaxContainer.length) { |
||||
pjaxContainer = $e.closest('[data-pjax-container]').attr('id') |
||||
? ('#' + $e.closest('[data-pjax-container]').attr('id')) |
||||
: ''; |
||||
} |
||||
if (!pjaxContainer.length) { |
||||
pjaxContainer = 'body'; |
||||
} |
||||
pjaxOptions = { |
||||
container: pjaxContainer, |
||||
push: !!$e.data('pjax-push-state'), |
||||
replace: !!$e.data('pjax-replace-state'), |
||||
scrollTo: $e.data('pjax-scrollto'), |
||||
pushRedirect: $e.data('pjax-push-redirect'), |
||||
replaceRedirect: $e.data('pjax-replace-redirect'), |
||||
skipOuterContainers: $e.data('pjax-skip-outer-containers'), |
||||
timeout: $e.data('pjax-timeout'), |
||||
originalEvent: event, |
||||
originalTarget: $e |
||||
}; |
||||
} |
||||
|
||||
if (method === undefined) { |
||||
if (isValidAction) { |
||||
usePjax ? $.pjax.click(event, pjaxOptions) : window.location.assign(action); |
||||
} else if ($e.is(':submit') && $form.length) { |
||||
if (usePjax) { |
||||
$form.on('submit', function (e) { |
||||
$.pjax.submit(e, pjaxOptions); |
||||
}); |
||||
} |
||||
$form.trigger('submit'); |
||||
} |
||||
return; |
||||
} |
||||
|
||||
var oldMethod, |
||||
oldAction, |
||||
newForm = !$form.length; |
||||
if (!newForm) { |
||||
oldMethod = $form.attr('method'); |
||||
$form.attr('method', method); |
||||
if (isValidAction) { |
||||
oldAction = $form.attr('action'); |
||||
$form.attr('action', action); |
||||
} |
||||
} else { |
||||
if (!isValidAction) { |
||||
action = pub.getCurrentUrl(); |
||||
} |
||||
$form = $('<form/>', {method: method, action: action}); |
||||
var target = $e.attr('target'); |
||||
if (target) { |
||||
$form.attr('target', target); |
||||
} |
||||
if (!/(get|post)/i.test(method)) { |
||||
$form.append($('<input/>', {name: '_method', value: method, type: 'hidden'})); |
||||
method = 'post'; |
||||
$form.attr('method', method); |
||||
} |
||||
if (/post/i.test(method)) { |
||||
var csrfParam = pub.getCsrfParam(); |
||||
if (csrfParam) { |
||||
$form.append($('<input/>', {name: csrfParam, value: pub.getCsrfToken(), type: 'hidden'})); |
||||
} |
||||
} |
||||
$form.hide().appendTo('body'); |
||||
} |
||||
|
||||
var activeFormData = $form.data('yiiActiveForm'); |
||||
if (activeFormData) { |
||||
// Remember the element triggered the form submission. This is used by yii.activeForm.js.
|
||||
activeFormData.submitObject = $e; |
||||
} |
||||
|
||||
if (areValidParams) { |
||||
$.each(params, function (name, value) { |
||||
$form.append($('<input/>').attr({name: name, value: value, type: 'hidden'})); |
||||
}); |
||||
} |
||||
|
||||
if (usePjax) { |
||||
$form.on('submit', function (e) { |
||||
$.pjax.submit(e, pjaxOptions); |
||||
}); |
||||
} |
||||
|
||||
$form.trigger('submit'); |
||||
|
||||
$.when($form.data('yiiSubmitFinalizePromise')).done(function () { |
||||
if (newForm) { |
||||
$form.remove(); |
||||
return; |
||||
} |
||||
|
||||
if (oldAction !== undefined) { |
||||
$form.attr('action', oldAction); |
||||
} |
||||
$form.attr('method', oldMethod); |
||||
|
||||
if (areValidParams) { |
||||
$.each(params, function (name) { |
||||
$('input[name="' + name + '"]', $form).remove(); |
||||
}); |
||||
} |
||||
}); |
||||
}, |
||||
|
||||
getQueryParams: function (url) { |
||||
var pos = url.indexOf('?'); |
||||
if (pos < 0) { |
||||
return {}; |
||||
} |
||||
|
||||
var pairs = $.grep(url.substring(pos + 1).split('#')[0].split('&'), function (value) { |
||||
return value !== ''; |
||||
}); |
||||
var params = {}; |
||||
|
||||
for (var i = 0, len = pairs.length; i < len; i++) { |
||||
var pair = pairs[i].split('='); |
||||
var name = decodeURIComponent(pair[0].replace(/\+/g, '%20')); |
||||
var value = decodeURIComponent(pair[1].replace(/\+/g, '%20')); |
||||
if (!name.length) { |
||||
continue; |
||||
} |
||||
if (params[name] === undefined) { |
||||
params[name] = value || ''; |
||||
} else { |
||||
if (!$.isArray(params[name])) { |
||||
params[name] = [params[name]]; |
||||
} |
||||
params[name].push(value || ''); |
||||
} |
||||
} |
||||
|
||||
return params; |
||||
}, |
||||
|
||||
initModule: function (module) { |
||||
if (module.isActive !== undefined && !module.isActive) { |
||||
return; |
||||
} |
||||
if ($.isFunction(module.init)) { |
||||
module.init(); |
||||
} |
||||
$.each(module, function () { |
||||
if ($.isPlainObject(this)) { |
||||
pub.initModule(this); |
||||
} |
||||
}); |
||||
}, |
||||
|
||||
init: function () { |
||||
initCsrfHandler(); |
||||
initRedirectHandler(); |
||||
initAssetFilters(); |
||||
initDataMethods(); |
||||
}, |
||||
|
||||
/** |
||||
* Returns the URL of the current page without params and trailing slash. Separated and made public for testing. |
||||
* @returns {string} |
||||
*/ |
||||
getBaseCurrentUrl: function () { |
||||
return window.location.protocol + '//' + window.location.host; |
||||
}, |
||||
|
||||
/** |
||||
* Returns the URL of the current page. Used for testing, you can always call `window.location.href` manually |
||||
* instead. |
||||
* @returns {string} |
||||
*/ |
||||
getCurrentUrl: function () { |
||||
return window.location.href; |
||||
} |
||||
}; |
||||
|
||||
function initCsrfHandler() { |
||||
// automatically send CSRF token for all AJAX requests
|
||||
$.ajaxPrefilter(function (options, originalOptions, xhr) { |
||||
if (!options.crossDomain && pub.getCsrfParam()) { |
||||
xhr.setRequestHeader('X-CSRF-Token', pub.getCsrfToken()); |
||||
} |
||||
}); |
||||
pub.refreshCsrfToken(); |
||||
} |
||||
|
||||
function initRedirectHandler() { |
||||
// handle AJAX redirection
|
||||
$(document).ajaxComplete(function (event, xhr) { |
||||
var url = xhr && xhr.getResponseHeader('X-Redirect'); |
||||
if (url) { |
||||
window.location.assign(url); |
||||
} |
||||
}); |
||||
} |
||||
|
||||
function initAssetFilters() { |
||||
/** |
||||
* Used for storing loaded scripts and information about loading each script if it's in the process of loading. |
||||
* A single script can have one of the following values: |
||||
* |
||||
* - `undefined` - script was not loaded at all before or was loaded with error last time. |
||||
* - `true` (boolean) - script was successfully loaded. |
||||
* - object - script is currently loading. |
||||
* |
||||
* In case of a value being an object the properties are: |
||||
* - `xhrList` - represents a queue of XHR requests sent to the same URL (related with this script) in the same |
||||
* small period of time. |
||||
* - `xhrDone` - boolean, acts like a locking mechanism. When one of the XHR requests in the queue is |
||||
* successfully completed, it will abort the rest of concurrent requests to the same URL until cleanup is done |
||||
* to prevent possible errors and race conditions. |
||||
* @type {{}} |
||||
*/ |
||||
var loadedScripts = {}; |
||||
|
||||
$('script[src]').each(function () { |
||||
var url = getAbsoluteUrl(this.src); |
||||
loadedScripts[url] = true; |
||||
}); |
||||
|
||||
$.ajaxPrefilter('script', function (options, originalOptions, xhr) { |
||||
if (options.dataType == 'jsonp') { |
||||
return; |
||||
} |
||||
|
||||
var url = getAbsoluteUrl(options.url), |
||||
forbiddenRepeatedLoad = loadedScripts[url] === true && !isReloadableAsset(url), |
||||
cleanupRunning = loadedScripts[url] !== undefined && loadedScripts[url]['xhrDone'] === true; |
||||
|
||||
if (forbiddenRepeatedLoad || cleanupRunning) { |
||||
xhr.abort(); |
||||
return; |
||||
} |
||||
|
||||
if (loadedScripts[url] === undefined || loadedScripts[url] === true) { |
||||
loadedScripts[url] = { |
||||
xhrList: [], |
||||
xhrDone: false |
||||
}; |
||||
} |
||||
|
||||
xhr.done(function (data, textStatus, jqXHR) { |
||||
// If multiple requests were successfully loaded, perform cleanup only once
|
||||
if (loadedScripts[jqXHR.yiiUrl]['xhrDone'] === true) { |
||||
return; |
||||
} |
||||
|
||||
loadedScripts[jqXHR.yiiUrl]['xhrDone'] = true; |
||||
|
||||
for (var i = 0, len = loadedScripts[jqXHR.yiiUrl]['xhrList'].length; i < len; i++) { |
||||
var singleXhr = loadedScripts[jqXHR.yiiUrl]['xhrList'][i]; |
||||
if (singleXhr && singleXhr.readyState !== XMLHttpRequest.DONE) { |
||||
singleXhr.abort(); |
||||
} |
||||
} |
||||
|
||||
loadedScripts[jqXHR.yiiUrl] = true; |
||||
}).fail(function (jqXHR, textStatus) { |
||||
if (textStatus === 'abort') { |
||||
return; |
||||
} |
||||
|
||||
delete loadedScripts[jqXHR.yiiUrl]['xhrList'][jqXHR.yiiIndex]; |
||||
|
||||
var allFailed = true; |
||||
for (var i = 0, len = loadedScripts[jqXHR.yiiUrl]['xhrList'].length; i < len; i++) { |
||||
if (loadedScripts[jqXHR.yiiUrl]['xhrList'][i]) { |
||||
allFailed = false; |
||||
} |
||||
} |
||||
|
||||
if (allFailed) { |
||||
delete loadedScripts[jqXHR.yiiUrl]; |
||||
} |
||||
}); |
||||
// Use prefix for custom XHR properties to avoid possible conflicts with existing properties
|
||||
xhr.yiiIndex = loadedScripts[url]['xhrList'].length; |
||||
xhr.yiiUrl = url; |
||||
|
||||
loadedScripts[url]['xhrList'][xhr.yiiIndex] = xhr; |
||||
}); |
||||
|
||||
$(document).ajaxComplete(function () { |
||||
var styleSheets = []; |
||||
$('link[rel=stylesheet]').each(function () { |
||||
var url = getAbsoluteUrl(this.href); |
||||
if (isReloadableAsset(url)) { |
||||
return; |
||||
} |
||||
|
||||
$.inArray(url, styleSheets) === -1 ? styleSheets.push(url) : $(this).remove(); |
||||
}); |
||||
}); |
||||
} |
||||
|
||||
function initDataMethods() { |
||||
var handler = function (event) { |
||||
var $this = $(this), |
||||
method = $this.data('method'), |
||||
message = $this.data('confirm'), |
||||
form = $this.data('form'); |
||||
|
||||
if (method === undefined && message === undefined && form === undefined) { |
||||
return true; |
||||
} |
||||
|
||||
if (message !== undefined) { |
||||
$.proxy(pub.confirm, this)(message, function () { |
||||
pub.handleAction($this, event); |
||||
}); |
||||
} else { |
||||
pub.handleAction($this, event); |
||||
} |
||||
event.stopImmediatePropagation(); |
||||
return false; |
||||
}; |
||||
|
||||
// handle data-confirm and data-method for clickable and changeable elements
|
||||
$(document).on('click.yii', pub.clickableSelector, handler) |
||||
.on('change.yii', pub.changeableSelector, handler); |
||||
} |
||||
|
||||
function isReloadableAsset(url) { |
||||
for (var i = 0; i < pub.reloadableScripts.length; i++) { |
||||
var rule = getAbsoluteUrl(pub.reloadableScripts[i]); |
||||
var match = new RegExp("^" + escapeRegExp(rule).split('\\*').join('.+') + "$").test(url); |
||||
if (match === true) { |
||||
return true; |
||||
} |
||||
} |
||||
|
||||
return false; |
||||
} |
||||
|
||||
// http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
|
||||
function escapeRegExp(str) { |
||||
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); |
||||
} |
||||
|
||||
/** |
||||
* Returns absolute URL based on the given URL |
||||
* @param {string} url Initial URL |
||||
* @returns {string} |
||||
*/ |
||||
function getAbsoluteUrl(url) { |
||||
return url.charAt(0) === '/' ? pub.getBaseCurrentUrl() + url : url; |
||||
} |
||||
|
||||
return pub; |
||||
})(window.jQuery); |
||||
|
||||
window.jQuery(function () { |
||||
window.yii.initModule(window.yii); |
||||
}); |
@ -1,452 +0,0 @@
|
||||
/** |
||||
* Yii validation module. |
||||
* |
||||
* This JavaScript module provides the validation methods for the built-in validators. |
||||
* |
||||
* @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 |
||||
*/ |
||||
|
||||
yii.validation = (function ($) { |
||||
var pub = { |
||||
isEmpty: function (value) { |
||||
return value === null || value === undefined || ($.isArray(value) && value.length === 0) || value === ''; |
||||
}, |
||||
|
||||
addMessage: function (messages, message, value) { |
||||
messages.push(message.replace(/\{value\}/g, value)); |
||||
}, |
||||
|
||||
required: function (value, messages, options) { |
||||
var valid = false; |
||||
if (options.requiredValue === undefined) { |
||||
var isString = typeof value == 'string' || value instanceof String; |
||||
if (options.strict && value !== undefined || !options.strict && !pub.isEmpty(isString ? $.trim(value) : value)) { |
||||
valid = true; |
||||
} |
||||
} else if (!options.strict && value == options.requiredValue || options.strict && value === options.requiredValue) { |
||||
valid = true; |
||||
} |
||||
|
||||
if (!valid) { |
||||
pub.addMessage(messages, options.message, value); |
||||
} |
||||
}, |
||||
|
||||
// "boolean" is a reserved keyword in older versions of ES so it's quoted for IE < 9 support
|
||||
'boolean': function (value, messages, options) { |
||||
if (options.skipOnEmpty && pub.isEmpty(value)) { |
||||
return; |
||||
} |
||||
var valid = !options.strict && (value == options.trueValue || value == options.falseValue) |
||||
|| options.strict && (value === options.trueValue || value === options.falseValue); |
||||
|
||||
if (!valid) { |
||||
pub.addMessage(messages, options.message, value); |
||||
} |
||||
}, |
||||
|
||||
string: function (value, messages, options) { |
||||
if (options.skipOnEmpty && pub.isEmpty(value)) { |
||||
return; |
||||
} |
||||
|
||||
if (typeof value !== 'string') { |
||||
pub.addMessage(messages, options.message, value); |
||||
return; |
||||
} |
||||
|
||||
if (options.is !== undefined && value.length != options.is) { |
||||
pub.addMessage(messages, options.notEqual, value); |
||||
return; |
||||
} |
||||
if (options.min !== undefined && value.length < options.min) { |
||||
pub.addMessage(messages, options.tooShort, value); |
||||
} |
||||
if (options.max !== undefined && value.length > options.max) { |
||||
pub.addMessage(messages, options.tooLong, value); |
||||
} |
||||
}, |
||||
|
||||
file: function (attribute, messages, options) { |
||||
var files = getUploadedFiles(attribute, messages, options); |
||||
$.each(files, function (i, file) { |
||||
validateFile(file, messages, options); |
||||
}); |
||||
}, |
||||
|
||||
image: function (attribute, messages, options, deferredList) { |
||||
var files = getUploadedFiles(attribute, messages, options); |
||||
$.each(files, function (i, file) { |
||||
validateFile(file, messages, options); |
||||
|
||||
// Skip image validation if FileReader API is not available
|
||||
if (typeof FileReader === "undefined") { |
||||
return; |
||||
} |
||||
|
||||
var deferred = $.Deferred(); |
||||
pub.validateImage(file, messages, options, deferred, new FileReader(), new Image()); |
||||
deferredList.push(deferred); |
||||
}); |
||||
}, |
||||
|
||||
validateImage: function (file, messages, options, deferred, fileReader, image) { |
||||
image.onload = function() { |
||||
validateImageSize(file, image, messages, options); |
||||
deferred.resolve(); |
||||
}; |
||||
|
||||
image.onerror = function () { |
||||
messages.push(options.notImage.replace(/\{file\}/g, file.name)); |
||||
deferred.resolve(); |
||||
}; |
||||
|
||||
fileReader.onload = function () { |
||||
image.src = this.result; |
||||
}; |
||||
|
||||
// Resolve deferred if there was error while reading data
|
||||
fileReader.onerror = function () { |
||||
deferred.resolve(); |
||||
}; |
||||
|
||||
fileReader.readAsDataURL(file); |
||||
}, |
||||
|
||||
number: function (value, messages, options) { |
||||
if (options.skipOnEmpty && pub.isEmpty(value)) { |
||||
return; |
||||
} |
||||
|
||||
if (typeof value === 'string' && !options.pattern.test(value)) { |
||||
pub.addMessage(messages, options.message, value); |
||||
return; |
||||
} |
||||
|
||||
if (options.min !== undefined && value < options.min) { |
||||
pub.addMessage(messages, options.tooSmall, value); |
||||
} |
||||
if (options.max !== undefined && value > options.max) { |
||||
pub.addMessage(messages, options.tooBig, value); |
||||
} |
||||
}, |
||||
|
||||
range: function (value, messages, options) { |
||||
if (options.skipOnEmpty && pub.isEmpty(value)) { |
||||
return; |
||||
} |
||||
|
||||
if (!options.allowArray && $.isArray(value)) { |
||||
pub.addMessage(messages, options.message, value); |
||||
return; |
||||
} |
||||
|
||||
var inArray = true; |
||||
|
||||
$.each($.isArray(value) ? value : [value], function (i, v) { |
||||
if ($.inArray(v, options.range) == -1) { |
||||
inArray = false; |
||||
return false; |
||||
} else { |
||||
return true; |
||||
} |
||||
}); |
||||
|
||||
if (options.not === undefined) { |
||||
options.not = false; |
||||
} |
||||
|
||||
if (options.not === inArray) { |
||||
pub.addMessage(messages, options.message, value); |
||||
} |
||||
}, |
||||
|
||||
regularExpression: function (value, messages, options) { |
||||
if (options.skipOnEmpty && pub.isEmpty(value)) { |
||||
return; |
||||
} |
||||
|
||||
if (!options.not && !options.pattern.test(value) || options.not && options.pattern.test(value)) { |
||||
pub.addMessage(messages, options.message, value); |
||||
} |
||||
}, |
||||
|
||||
email: function (value, messages, options) { |
||||
if (options.skipOnEmpty && pub.isEmpty(value)) { |
||||
return; |
||||
} |
||||
|
||||
var valid = true, |
||||
regexp = /^((?:"?([^"]*)"?\s)?)(?:\s+)?(?:(<?)((.+)@([^>]+))(>?))$/, |
||||
matches = regexp.exec(value); |
||||
|
||||
if (matches === null) { |
||||
valid = false; |
||||
} else { |
||||
var localPart = matches[5], |
||||
domain = matches[6]; |
||||
|
||||
if (options.enableIDN) { |
||||
localPart = punycode.toASCII(localPart); |
||||
domain = punycode.toASCII(domain); |
||||
|
||||
value = matches[1] + matches[3] + localPart + '@' + domain + matches[7]; |
||||
} |
||||
|
||||
if (localPart.length > 64) { |
||||
valid = false; |
||||
} else if ((localPart + '@' + domain).length > 254) { |
||||
valid = false; |
||||
} else { |
||||
valid = options.pattern.test(value) || (options.allowName && options.fullPattern.test(value)); |
||||
} |
||||
} |
||||
|
||||
if (!valid) { |
||||
pub.addMessage(messages, options.message, value); |
||||
} |
||||
}, |
||||
|
||||
url: function (value, messages, options) { |
||||
if (options.skipOnEmpty && pub.isEmpty(value)) { |
||||
return; |
||||
} |
||||
|
||||
if (options.defaultScheme && !/:\/\//.test(value)) { |
||||
value = options.defaultScheme + '://' + value; |
||||
} |
||||
|
||||
var valid = true; |
||||
|
||||
if (options.enableIDN) { |
||||
var matches = /^([^:]+):\/\/([^\/]+)(.*)$/.exec(value); |
||||
if (matches === null) { |
||||
valid = false; |
||||
} else { |
||||
value = matches[1] + '://' + punycode.toASCII(matches[2]) + matches[3]; |
||||
} |
||||
} |
||||
|
||||
if (!valid || !options.pattern.test(value)) { |
||||
pub.addMessage(messages, options.message, value); |
||||
} |
||||
}, |
||||
|
||||
trim: function ($form, attribute, options) { |
||||
var $input = $form.find(attribute.input); |
||||
var value = $input.val(); |
||||
if (!options.skipOnEmpty || !pub.isEmpty(value)) { |
||||
value = $.trim(value); |
||||
$input.val(value); |
||||
} |
||||
|
||||
return value; |
||||
}, |
||||
|
||||
captcha: function (value, messages, options) { |
||||
if (options.skipOnEmpty && pub.isEmpty(value)) { |
||||
return; |
||||
} |
||||
|
||||
// CAPTCHA may be updated via AJAX and the updated hash is stored in body data
|
||||
var hash = $('body').data(options.hashKey); |
||||
hash = hash == null ? options.hash : hash[options.caseSensitive ? 0 : 1]; |
||||
var v = options.caseSensitive ? value : value.toLowerCase(); |
||||
for (var i = v.length - 1, h = 0; i >= 0; --i) { |
||||
h += v.charCodeAt(i); |
||||
} |
||||
if (h != hash) { |
||||
pub.addMessage(messages, options.message, value); |
||||
} |
||||
}, |
||||
|
||||
compare: function (value, messages, options, $form) { |
||||
if (options.skipOnEmpty && pub.isEmpty(value)) { |
||||
return; |
||||
} |
||||
|
||||
var compareValue, |
||||
valid = true; |
||||
if (options.compareAttribute === undefined) { |
||||
compareValue = options.compareValue; |
||||
} else { |
||||
var attributes = $form.data('yiiActiveForm').attributes |
||||
for (var i = attributes.length - 1; i >= 0; i--) { |
||||
if (attributes[i].id === options.compareAttribute) { |
||||
compareValue = $(attributes[i].input).val(); |
||||
} |
||||
} |
||||
} |
||||
|
||||
if (options.type === 'number') { |
||||
value = parseFloat(value); |
||||
compareValue = parseFloat(compareValue); |
||||
} |
||||
switch (options.operator) { |
||||
case '==': |
||||
valid = value == compareValue; |
||||
break; |
||||
case '===': |
||||
valid = value === compareValue; |
||||
break; |
||||
case '!=': |
||||
valid = value != compareValue; |
||||
break; |
||||
case '!==': |
||||
valid = value !== compareValue; |
||||
break; |
||||
case '>': |
||||
valid = value > compareValue; |
||||
break; |
||||
case '>=': |
||||
valid = value >= compareValue; |
||||
break; |
||||
case '<': |
||||
valid = value < compareValue; |
||||
break; |
||||
case '<=': |
||||
valid = value <= compareValue; |
||||
break; |
||||
default: |
||||
valid = false; |
||||
break; |
||||
} |
||||
|
||||
if (!valid) { |
||||
pub.addMessage(messages, options.message, value); |
||||
} |
||||
}, |
||||
|
||||
ip: function (value, messages, options) { |
||||
if (options.skipOnEmpty && pub.isEmpty(value)) { |
||||
return; |
||||
} |
||||
|
||||
var negation = null, |
||||
cidr = null, |
||||
matches = new RegExp(options.ipParsePattern).exec(value); |
||||
if (matches) { |
||||
negation = matches[1] || null; |
||||
value = matches[2]; |
||||
cidr = matches[4] || null; |
||||
} |
||||
|
||||
if (options.subnet === true && cidr === null) { |
||||
pub.addMessage(messages, options.messages.noSubnet, value); |
||||
return; |
||||
} |
||||
if (options.subnet === false && cidr !== null) { |
||||
pub.addMessage(messages, options.messages.hasSubnet, value); |
||||
return; |
||||
} |
||||
if (options.negation === false && negation !== null) { |
||||
pub.addMessage(messages, options.messages.message, value); |
||||
return; |
||||
} |
||||
|
||||
var ipVersion = value.indexOf(':') === -1 ? 4 : 6; |
||||
if (ipVersion == 6) { |
||||
if (!(new RegExp(options.ipv6Pattern)).test(value)) { |
||||
pub.addMessage(messages, options.messages.message, value); |
||||
} |
||||
if (!options.ipv6) { |
||||
pub.addMessage(messages, options.messages.ipv6NotAllowed, value); |
||||
} |
||||
} else { |
||||
if (!(new RegExp(options.ipv4Pattern)).test(value)) { |
||||
pub.addMessage(messages, options.messages.message, value); |
||||
} |
||||
if (!options.ipv4) { |
||||
pub.addMessage(messages, options.messages.ipv4NotAllowed, value); |
||||
} |
||||
} |
||||
} |
||||
}; |
||||
|
||||
function getUploadedFiles(attribute, messages, options) { |
||||
// Skip validation if File API is not available
|
||||
if (typeof File === "undefined") { |
||||
return []; |
||||
} |
||||
|
||||
var files = $(attribute.input, attribute.$form).get(0).files; |
||||
if (!files) { |
||||
messages.push(options.message); |
||||
return []; |
||||
} |
||||
|
||||
if (files.length === 0) { |
||||
if (!options.skipOnEmpty) { |
||||
messages.push(options.uploadRequired); |
||||
} |
||||
|
||||
return []; |
||||
} |
||||
|
||||
if (options.maxFiles && options.maxFiles < files.length) { |
||||
messages.push(options.tooMany); |
||||
return []; |
||||
} |
||||
|
||||
return files; |
||||
} |
||||
|
||||
function validateFile(file, messages, options) { |
||||
if (options.extensions && options.extensions.length > 0) { |
||||
var index = file.name.lastIndexOf('.'); |
||||
var ext = !~index ? '' : file.name.substr(index + 1, file.name.length).toLowerCase(); |
||||
|
||||
if (!~options.extensions.indexOf(ext)) { |
||||
messages.push(options.wrongExtension.replace(/\{file\}/g, file.name)); |
||||
} |
||||
} |
||||
|
||||
if (options.mimeTypes && options.mimeTypes.length > 0) { |
||||
if (!validateMimeType(options.mimeTypes, file.type)) { |
||||
messages.push(options.wrongMimeType.replace(/\{file\}/g, file.name)); |
||||
} |
||||
} |
||||
|
||||
if (options.maxSize && options.maxSize < file.size) { |
||||
messages.push(options.tooBig.replace(/\{file\}/g, file.name)); |
||||
} |
||||
|
||||
if (options.minSize && options.minSize > file.size) { |
||||
messages.push(options.tooSmall.replace(/\{file\}/g, file.name)); |
||||
} |
||||
} |
||||
|
||||
function validateMimeType(mimeTypes, fileType) { |
||||
for (var i = 0, len = mimeTypes.length; i < len; i++) { |
||||
if (new RegExp(mimeTypes[i]).test(fileType)) { |
||||
return true; |
||||
} |
||||
} |
||||
|
||||
return false; |
||||
} |
||||
|
||||
function validateImageSize(file, image, messages, options) { |
||||
if (options.minWidth && image.width < options.minWidth) { |
||||
messages.push(options.underWidth.replace(/\{file\}/g, file.name)); |
||||
} |
||||
|
||||
if (options.maxWidth && image.width > options.maxWidth) { |
||||
messages.push(options.overWidth.replace(/\{file\}/g, file.name)); |
||||
} |
||||
|
||||
if (options.minHeight && image.height < options.minHeight) { |
||||
messages.push(options.underHeight.replace(/\{file\}/g, file.name)); |
||||
} |
||||
|
||||
if (options.maxHeight && image.height > options.maxHeight) { |
||||
messages.push(options.overHeight.replace(/\{file\}/g, file.name)); |
||||
} |
||||
} |
||||
|
||||
return pub; |
||||
})(jQuery); |
@ -1,61 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery\validators\client; |
||||
|
||||
use yii\jquery\ValidationAsset; |
||||
use yii\validators\client\ClientValidator; |
||||
|
||||
/** |
||||
* BooleanValidator composes client-side validation code from [[\yii\validators\BooleanValidator]]. |
||||
* |
||||
* @see \yii\validators\BooleanValidator |
||||
* @see ValidationAsset |
||||
* |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class BooleanValidator extends ClientValidator |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public function build($validator, $model, $attribute, $view) |
||||
{ |
||||
ValidationAsset::register($view); |
||||
$options = $this->getClientOptions($validator, $model, $attribute); |
||||
return 'yii.validation.boolean(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');'; |
||||
} |
||||
|
||||
/** |
||||
* Returns the client-side validation options. |
||||
* @param \yii\validators\BooleanValidator $validator the server-side validator. |
||||
* @param \yii\base\Model $model the model being validated |
||||
* @param string $attribute the attribute name being validated |
||||
* @return array the client-side validation options |
||||
*/ |
||||
public function getClientOptions($validator, $model, $attribute) |
||||
{ |
||||
$options = [ |
||||
'trueValue' => $validator->trueValue, |
||||
'falseValue' => $validator->falseValue, |
||||
'message' => $validator->formatMessage($validator->message, [ |
||||
'attribute' => $model->getAttributeLabel($attribute), |
||||
'true' => $validator->trueValue === true ? 'true' : $validator->trueValue, |
||||
'false' => $validator->falseValue === false ? 'false' : $validator->falseValue, |
||||
]), |
||||
]; |
||||
if ($validator->skipOnEmpty) { |
||||
$options['skipOnEmpty'] = 1; |
||||
} |
||||
if ($validator->strict) { |
||||
$options['strict'] = 1; |
||||
} |
||||
|
||||
return $options; |
||||
} |
||||
} |
@ -1,60 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery\validators\client; |
||||
|
||||
use yii\jquery\ValidationAsset; |
||||
use yii\validators\client\ClientValidator; |
||||
|
||||
/** |
||||
* CaptchaClientValidator composes client-side validation code from [[CaptchaValidator]]. |
||||
* |
||||
* @see CaptchaValidator |
||||
* @see ValidationAsset |
||||
* |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class CaptchaClientValidator extends ClientValidator |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public function build($validator, $model, $attribute, $view) |
||||
{ |
||||
ValidationAsset::register($view); |
||||
$options = $this->getClientOptions($validator, $model, $attribute); |
||||
return 'yii.validation.captcha(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');'; |
||||
} |
||||
|
||||
/** |
||||
* Returns the client-side validation options. |
||||
* @param \yii\captcha\CaptchaValidator $validator the server-side validator. |
||||
* @param \yii\base\Model $model the model being validated |
||||
* @param string $attribute the attribute name being validated |
||||
* @return array the client-side validation options |
||||
*/ |
||||
public function getClientOptions($validator, $model, $attribute) |
||||
{ |
||||
$captcha = $validator->createCaptchaAction(); |
||||
$code = $captcha->getVerifyCode(false); |
||||
$hash = $captcha->generateValidationHash($validator->caseSensitive ? $code : strtolower($code)); |
||||
$options = [ |
||||
'hash' => $hash, |
||||
'hashKey' => 'yiiCaptcha/' . $captcha->getUniqueId(), |
||||
'caseSensitive' => $validator->caseSensitive, |
||||
'message' => $validator->formatMessage($validator->message, [ |
||||
'attribute' => $model->getAttributeLabel($attribute), |
||||
]), |
||||
]; |
||||
if ($validator->skipOnEmpty) { |
||||
$options['skipOnEmpty'] = 1; |
||||
} |
||||
|
||||
return $options; |
||||
} |
||||
} |
@ -1,72 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery\validators\client; |
||||
|
||||
use yii\helpers\Html; |
||||
use yii\jquery\ValidationAsset; |
||||
use yii\validators\client\ClientValidator; |
||||
|
||||
/** |
||||
* CompareValidator composes client-side validation code from [[\yii\validators\CompareValidator]]. |
||||
* |
||||
* @see \yii\validators\CompareValidator |
||||
* @see ValidationAsset |
||||
* |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class CompareValidator extends ClientValidator |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public function build($validator, $model, $attribute, $view) |
||||
{ |
||||
ValidationAsset::register($view); |
||||
$options = $this->getClientOptions($validator, $model, $attribute); |
||||
return 'yii.validation.compare(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');'; |
||||
} |
||||
|
||||
/** |
||||
* Returns the client-side validation options. |
||||
* @param \yii\validators\CompareValidator $validator the server-side validator. |
||||
* @param \yii\base\Model $model the model being validated |
||||
* @param string $attribute the attribute name being validated |
||||
* @return array the client-side validation options |
||||
*/ |
||||
public function getClientOptions($validator, $model, $attribute) |
||||
{ |
||||
$options = [ |
||||
'operator' => $validator->operator, |
||||
'type' => $validator->type, |
||||
]; |
||||
|
||||
if ($validator->compareValue !== null) { |
||||
$options['compareValue'] = $validator->compareValue; |
||||
$compareLabel = $compareValue = $compareValueOrAttribute = $validator->compareValue; |
||||
} else { |
||||
$compareAttribute = $validator->compareAttribute === null ? $attribute . '_repeat' : $validator->compareAttribute; |
||||
$compareValue = $model->getAttributeLabel($compareAttribute); |
||||
$options['compareAttribute'] = Html::getInputId($model, $compareAttribute); |
||||
$compareLabel = $compareValueOrAttribute = $model->getAttributeLabel($compareAttribute); |
||||
} |
||||
|
||||
if ($validator->skipOnEmpty) { |
||||
$options['skipOnEmpty'] = 1; |
||||
} |
||||
|
||||
$options['message'] = $validator->formatMessage($validator->message, [ |
||||
'attribute' => $model->getAttributeLabel($attribute), |
||||
'compareAttribute' => $compareLabel, |
||||
'compareValue' => $compareValue, |
||||
'compareValueOrAttribute' => $compareValueOrAttribute, |
||||
]); |
||||
|
||||
return $options; |
||||
} |
||||
} |
@ -1,65 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery\validators\client; |
||||
|
||||
use yii\helpers\Json; |
||||
use yii\jquery\PunycodeAsset; |
||||
use yii\jquery\ValidationAsset; |
||||
use yii\validators\client\ClientValidator; |
||||
use yii\web\JsExpression; |
||||
|
||||
/** |
||||
* EmailValidator composes client-side validation code from [[\yii\validators\EmailValidator]]. |
||||
* |
||||
* @see \yii\validators\EmailValidator |
||||
* @see ValidationAsset |
||||
* |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class EmailValidator extends ClientValidator |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public function build($validator, $model, $attribute, $view) |
||||
{ |
||||
/* @var $validator \yii\validators\EmailValidator */ |
||||
ValidationAsset::register($view); |
||||
if ($validator->enableIDN) { |
||||
PunycodeAsset::register($view); |
||||
} |
||||
$options = $this->getClientOptions($validator, $model, $attribute); |
||||
return 'yii.validation.email(value, messages, ' . Json::htmlEncode($options) . ');'; |
||||
} |
||||
|
||||
/** |
||||
* Returns the client-side validation options. |
||||
* @param \yii\validators\EmailValidator $validator the server-side validator. |
||||
* @param \yii\base\Model $model the model being validated |
||||
* @param string $attribute the attribute name being validated |
||||
* @return array the client-side validation options |
||||
*/ |
||||
public function getClientOptions($validator, $model, $attribute) |
||||
{ |
||||
$options = [ |
||||
'pattern' => new JsExpression($validator->pattern), |
||||
'fullPattern' => new JsExpression($validator->fullPattern), |
||||
'allowName' => $validator->allowName, |
||||
'message' => $validator->formatMessage($validator->message, [ |
||||
'attribute' => $model->getAttributeLabel($attribute), |
||||
]), |
||||
'enableIDN' => (bool)$validator->enableIDN, |
||||
]; |
||||
if ($validator->skipOnEmpty) { |
||||
$options['skipOnEmpty'] = 1; |
||||
} |
||||
|
||||
return $options; |
||||
} |
||||
} |
@ -1,112 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery\validators\client; |
||||
|
||||
use Yii; |
||||
use yii\helpers\Html; |
||||
use yii\helpers\Json; |
||||
use yii\jquery\ValidationAsset; |
||||
use yii\validators\client\ClientValidator; |
||||
use yii\web\JsExpression; |
||||
|
||||
/** |
||||
* FileValidator composes client-side validation code from [[\yii\validators\FileValidator]]. |
||||
* |
||||
* @see \yii\validators\FileValidator |
||||
* @see ValidationAsset |
||||
* |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class FileValidator extends ClientValidator |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public function build($validator, $model, $attribute, $view) |
||||
{ |
||||
ValidationAsset::register($view); |
||||
$options = $this->getClientOptions($validator, $model, $attribute); |
||||
return 'yii.validation.file(attribute, messages, ' . Json::encode($options) . ');'; |
||||
} |
||||
|
||||
/** |
||||
* Returns the client-side validation options. |
||||
* @param \yii\validators\FileValidator $validator the server-side validator. |
||||
* @param \yii\base\Model $model the model being validated |
||||
* @param string $attribute the attribute name being validated |
||||
* @return array the client-side validation options |
||||
*/ |
||||
public function getClientOptions($validator, $model, $attribute) |
||||
{ |
||||
$label = $model->getAttributeLabel($attribute); |
||||
|
||||
$options = []; |
||||
if ($validator->message !== null) { |
||||
$options['message'] = $validator->formatMessage($validator->message, [ |
||||
'attribute' => $label, |
||||
]); |
||||
} |
||||
|
||||
$options['skipOnEmpty'] = $validator->skipOnEmpty; |
||||
|
||||
if (!$validator->skipOnEmpty) { |
||||
$options['uploadRequired'] = $validator->formatMessage($validator->uploadRequired, [ |
||||
'attribute' => $label, |
||||
]); |
||||
} |
||||
|
||||
if ($validator->mimeTypes !== null) { |
||||
$mimeTypes = []; |
||||
foreach ($validator->mimeTypes as $mimeType) { |
||||
$mimeTypes[] = new JsExpression(Html::escapeJsRegularExpression($validator->buildMimeTypeRegexp($mimeType))); |
||||
} |
||||
$options['mimeTypes'] = $mimeTypes; |
||||
$options['wrongMimeType'] = $validator->formatMessage($validator->wrongMimeType, [ |
||||
'attribute' => $label, |
||||
'mimeTypes' => implode(', ', $validator->mimeTypes), |
||||
]); |
||||
} |
||||
|
||||
if ($validator->extensions !== null) { |
||||
$options['extensions'] = $validator->extensions; |
||||
$options['wrongExtension'] = $validator->formatMessage($validator->wrongExtension, [ |
||||
'attribute' => $label, |
||||
'extensions' => implode(', ', $validator->extensions), |
||||
]); |
||||
} |
||||
|
||||
if ($validator->minSize !== null) { |
||||
$options['minSize'] = $validator->minSize; |
||||
$options['tooSmall'] = $validator->formatMessage($validator->tooSmall, [ |
||||
'attribute' => $label, |
||||
'limit' => $validator->minSize, |
||||
'formattedLimit' => Yii::$app->formatter->asShortSize($validator->minSize), |
||||
]); |
||||
} |
||||
|
||||
if ($validator->maxSize !== null) { |
||||
$options['maxSize'] = $validator->maxSize; |
||||
$options['tooBig'] = $validator->formatMessage($validator->tooBig, [ |
||||
'attribute' => $label, |
||||
'limit' => $validator->getSizeLimit(), |
||||
'formattedLimit' => Yii::$app->formatter->asShortSize($validator->getSizeLimit()), |
||||
]); |
||||
} |
||||
|
||||
if ($validator->maxFiles !== null) { |
||||
$options['maxFiles'] = $validator->maxFiles; |
||||
$options['tooMany'] = $validator->formatMessage($validator->tooMany, [ |
||||
'attribute' => $label, |
||||
'limit' => $validator->maxFiles, |
||||
]); |
||||
} |
||||
|
||||
return $options; |
||||
} |
||||
} |
@ -1,50 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery\validators\client; |
||||
|
||||
use yii\jquery\ValidationAsset; |
||||
use yii\validators\client\ClientValidator; |
||||
|
||||
/** |
||||
* FilterValidator composes client-side validation code from [[\yii\validators\FilterValidator]]. |
||||
* |
||||
* @see \yii\validators\FilterValidator |
||||
* @see ValidationAsset |
||||
* |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class FilterValidator extends ClientValidator |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public function build($validator, $model, $attribute, $view) |
||||
{ |
||||
ValidationAsset::register($view); |
||||
$options = $this->getClientOptions($validator, $model, $attribute); |
||||
return 'value = yii.validation.trim($form, attribute, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');'; |
||||
} |
||||
|
||||
/** |
||||
* Returns the client-side validation options. |
||||
* @param \yii\validators\FilterValidator $validator the server-side validator. |
||||
* @param \yii\base\Model $model the model being validated |
||||
* @param string $attribute the attribute name being validated |
||||
* @return array the client-side validation options |
||||
*/ |
||||
public function getClientOptions($validator, $model, $attribute) |
||||
{ |
||||
$options = []; |
||||
if ($validator->skipOnEmpty) { |
||||
$options['skipOnEmpty'] = 1; |
||||
} |
||||
|
||||
return $options; |
||||
} |
||||
} |
@ -1,86 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery\validators\client; |
||||
|
||||
use yii\jquery\ValidationAsset; |
||||
|
||||
/** |
||||
* ImageValidator composes client-side validation code from [[\yii\validators\ImageValidator]]. |
||||
* |
||||
* @see \yii\validators\ImageValidator |
||||
* @see ValidationAsset |
||||
* |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class ImageValidator extends FileValidator |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public function build($validator, $model, $attribute, $view) |
||||
{ |
||||
ValidationAsset::register($view); |
||||
$options = $this->getClientOptions($validator, $model, $attribute); |
||||
return 'yii.validation.image(attribute, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ', deferred);'; |
||||
} |
||||
|
||||
/** |
||||
* Returns the client-side validation options. |
||||
* @param \yii\validators\ImageValidator $validator the server-side validator. |
||||
* @param \yii\base\Model $model the model being validated |
||||
* @param string $attribute the attribute name being validated |
||||
* @return array the client-side validation options |
||||
*/ |
||||
public function getClientOptions($validator, $model, $attribute) |
||||
{ |
||||
$options = parent::getClientOptions($validator, $model, $attribute); |
||||
|
||||
$label = $model->getAttributeLabel($attribute); |
||||
|
||||
if ($validator->notImage !== null) { |
||||
$options['notImage'] = $validator->formatMessage($validator->notImage, [ |
||||
'attribute' => $label, |
||||
]); |
||||
} |
||||
|
||||
if ($validator->minWidth !== null) { |
||||
$options['minWidth'] = $validator->minWidth; |
||||
$options['underWidth'] = $validator->formatMessage($validator->underWidth, [ |
||||
'attribute' => $label, |
||||
'limit' => $validator->minWidth, |
||||
]); |
||||
} |
||||
|
||||
if ($validator->maxWidth !== null) { |
||||
$options['maxWidth'] = $validator->maxWidth; |
||||
$options['overWidth'] = $validator->formatMessage($validator->overWidth, [ |
||||
'attribute' => $label, |
||||
'limit' => $validator->maxWidth, |
||||
]); |
||||
} |
||||
|
||||
if ($validator->minHeight !== null) { |
||||
$options['minHeight'] = $validator->minHeight; |
||||
$options['underHeight'] = $validator->formatMessage($validator->underHeight, [ |
||||
'attribute' => $label, |
||||
'limit' => $validator->minHeight, |
||||
]); |
||||
} |
||||
|
||||
if ($validator->maxHeight !== null) { |
||||
$options['maxHeight'] = $validator->maxHeight; |
||||
$options['overHeight'] = $validator->formatMessage($validator->overHeight, [ |
||||
'attribute' => $label, |
||||
'limit' => $validator->maxHeight, |
||||
]); |
||||
} |
||||
|
||||
return $options; |
||||
} |
||||
} |
@ -1,76 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery\validators\client; |
||||
|
||||
use Yii; |
||||
use yii\helpers\Html; |
||||
use yii\helpers\Json; |
||||
use yii\jquery\ValidationAsset; |
||||
use yii\validators\client\ClientValidator; |
||||
use yii\web\JsExpression; |
||||
|
||||
/** |
||||
* IpValidator composes client-side validation code from [[\yii\validators\IpValidator]]. |
||||
* |
||||
* @see \yii\validators\IpValidator |
||||
* @see ValidationAsset |
||||
* |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class IpValidator extends ClientValidator |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public function build($validator, $model, $attribute, $view) |
||||
{ |
||||
ValidationAsset::register($view); |
||||
$options = $this->getClientOptions($validator, $model, $attribute); |
||||
return 'yii.validation.ip(value, messages, ' . Json::htmlEncode($options) . ');'; |
||||
} |
||||
|
||||
/** |
||||
* Returns the client-side validation options. |
||||
* @param \yii\validators\IpValidator $validator the server-side validator. |
||||
* @param \yii\base\Model $model the model being validated |
||||
* @param string $attribute the attribute name being validated |
||||
* @return array the client-side validation options |
||||
*/ |
||||
public function getClientOptions($validator, $model, $attribute) |
||||
{ |
||||
$messages = [ |
||||
'ipv6NotAllowed' => $validator->ipv6NotAllowed, |
||||
'ipv4NotAllowed' => $validator->ipv4NotAllowed, |
||||
'message' => $validator->message, |
||||
'noSubnet' => $validator->noSubnet, |
||||
'hasSubnet' => $validator->hasSubnet, |
||||
]; |
||||
foreach ($messages as &$message) { |
||||
$message = $validator->formatMessage($message, [ |
||||
'attribute' => $model->getAttributeLabel($attribute), |
||||
]); |
||||
} |
||||
|
||||
$options = [ |
||||
'ipv4Pattern' => new JsExpression(Html::escapeJsRegularExpression($validator->ipv4Pattern)), |
||||
'ipv6Pattern' => new JsExpression(Html::escapeJsRegularExpression($validator->ipv6Pattern)), |
||||
'messages' => $messages, |
||||
'ipv4' => (bool) $validator->ipv4, |
||||
'ipv6' => (bool) $validator->ipv6, |
||||
'ipParsePattern' => new JsExpression(Html::escapeJsRegularExpression($validator->getIpParsePattern())), |
||||
'negation' => $validator->negation, |
||||
'subnet' => $validator->subnet, |
||||
]; |
||||
if ($validator->skipOnEmpty) { |
||||
$options['skipOnEmpty'] = 1; |
||||
} |
||||
|
||||
return $options; |
||||
} |
||||
} |
@ -1,78 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery\validators\client; |
||||
|
||||
use yii\helpers\Json; |
||||
use yii\jquery\ValidationAsset; |
||||
use yii\validators\client\ClientValidator; |
||||
use yii\web\JsExpression; |
||||
|
||||
/** |
||||
* NumberValidator composes client-side validation code from [[\yii\validators\NumberValidator]]. |
||||
* |
||||
* @see \yii\validators\NumberValidator |
||||
* @see ValidationAsset |
||||
* |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class NumberValidator extends ClientValidator |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public function build($validator, $model, $attribute, $view) |
||||
{ |
||||
ValidationAsset::register($view); |
||||
$options = $this->getClientOptions($validator, $model, $attribute); |
||||
return 'yii.validation.number(value, messages, ' . Json::htmlEncode($options) . ');'; |
||||
} |
||||
|
||||
/** |
||||
* Returns the client-side validation options. |
||||
* @param \yii\validators\NumberValidator $validator the server-side validator. |
||||
* @param \yii\base\Model $model the model being validated |
||||
* @param string $attribute the attribute name being validated |
||||
* @return array the client-side validation options |
||||
*/ |
||||
public function getClientOptions($validator, $model, $attribute) |
||||
{ |
||||
$label = $model->getAttributeLabel($attribute); |
||||
|
||||
$options = [ |
||||
'pattern' => new JsExpression($validator->integerOnly ? $validator->integerPattern : $validator->numberPattern), |
||||
'message' => $validator->formatMessage($validator->message, [ |
||||
'attribute' => $label, |
||||
]), |
||||
]; |
||||
|
||||
if ($validator->min !== null) { |
||||
// ensure numeric value to make javascript comparison equal to PHP comparison |
||||
// https://github.com/yiisoft/yii2/issues/3118 |
||||
$options['min'] = is_string($validator->min) ? (float) $validator->min : $validator->min; |
||||
$options['tooSmall'] = $validator->formatMessage($validator->tooSmall, [ |
||||
'attribute' => $label, |
||||
'min' => $validator->min, |
||||
]); |
||||
} |
||||
if ($validator->max !== null) { |
||||
// ensure numeric value to make javascript comparison equal to PHP comparison |
||||
// https://github.com/yiisoft/yii2/issues/3118 |
||||
$options['max'] = is_string($validator->max) ? (float) $validator->max : $validator->max; |
||||
$options['tooBig'] = $validator->formatMessage($validator->tooBig, [ |
||||
'attribute' => $label, |
||||
'max' => $validator->max, |
||||
]); |
||||
} |
||||
if ($validator->skipOnEmpty) { |
||||
$options['skipOnEmpty'] = 1; |
||||
} |
||||
|
||||
return $options; |
||||
} |
||||
} |
@ -1,67 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery\validators\client; |
||||
|
||||
use yii\jquery\ValidationAsset; |
||||
use yii\validators\client\ClientValidator; |
||||
|
||||
/** |
||||
* RangeValidator composes client-side validation code from [[\yii\validators\RangeValidator]]. |
||||
* |
||||
* @see \yii\validators\RangeValidator |
||||
* @see ValidationAsset |
||||
* |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class RangeValidator extends ClientValidator |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public function build($validator, $model, $attribute, $view) |
||||
{ |
||||
/* @var $validator \yii\validators\RangeValidator */ |
||||
if ($validator->range instanceof \Closure) { |
||||
$validator->range = call_user_func($validator->range, $model, $attribute); |
||||
} |
||||
ValidationAsset::register($view); |
||||
$options = $validator->getClientOptions($model, $attribute); |
||||
return 'yii.validation.range(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');'; |
||||
} |
||||
|
||||
/** |
||||
* Returns the client-side validation options. |
||||
* @param \yii\validators\RangeValidator $validator the server-side validator. |
||||
* @param \yii\base\Model $model the model being validated |
||||
* @param string $attribute the attribute name being validated |
||||
* @return array the client-side validation options |
||||
*/ |
||||
public function getClientOptions($validator, $model, $attribute) |
||||
{ |
||||
$range = []; |
||||
foreach ($validator->range as $value) { |
||||
$range[] = (string) $value; |
||||
} |
||||
$options = [ |
||||
'range' => $range, |
||||
'not' => $validator->not, |
||||
'message' => $validator->formatMessage($validator->message, [ |
||||
'attribute' => $model->getAttributeLabel($attribute), |
||||
]), |
||||
]; |
||||
if ($validator->skipOnEmpty) { |
||||
$options['skipOnEmpty'] = 1; |
||||
} |
||||
if ($validator->allowArray) { |
||||
$options['allowArray'] = 1; |
||||
} |
||||
|
||||
return $options; |
||||
} |
||||
} |
@ -1,61 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery\validators\client; |
||||
|
||||
use yii\helpers\Html; |
||||
use yii\helpers\Json; |
||||
use yii\jquery\ValidationAsset; |
||||
use yii\validators\client\ClientValidator; |
||||
use yii\web\JsExpression; |
||||
|
||||
/** |
||||
* RegularExpressionValidator composes client-side validation code from [[\yii\validators\RegularExpressionValidator]]. |
||||
* |
||||
* @see \yii\validators\RegularExpressionValidator |
||||
* @see ValidationAsset |
||||
* |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class RegularExpressionValidator extends ClientValidator |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public function build($validator, $model, $attribute, $view) |
||||
{ |
||||
ValidationAsset::register($view); |
||||
$options = $this->getClientOptions($validator, $model, $attribute); |
||||
return 'yii.validation.regularExpression(value, messages, ' . Json::htmlEncode($options) . ');'; |
||||
} |
||||
|
||||
/** |
||||
* Returns the client-side validation options. |
||||
* @param \yii\validators\RegularExpressionValidator $validator the server-side validator. |
||||
* @param \yii\base\Model $model the model being validated |
||||
* @param string $attribute the attribute name being validated |
||||
* @return array the client-side validation options |
||||
*/ |
||||
public function getClientOptions($validator, $model, $attribute) |
||||
{ |
||||
$pattern = Html::escapeJsRegularExpression($validator->pattern); |
||||
|
||||
$options = [ |
||||
'pattern' => new JsExpression($pattern), |
||||
'not' => $validator->not, |
||||
'message' => $validator->formatMessage($validator->message, [ |
||||
'attribute' => $model->getAttributeLabel($attribute), |
||||
]), |
||||
]; |
||||
if ($validator->skipOnEmpty) { |
||||
$options['skipOnEmpty'] = 1; |
||||
} |
||||
|
||||
return $options; |
||||
} |
||||
} |
@ -1,62 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery\validators\client; |
||||
|
||||
use yii\jquery\ValidationAsset; |
||||
use yii\validators\client\ClientValidator; |
||||
|
||||
/** |
||||
* RequiredValidator composes client-side validation code from [[\yii\validators\RequiredValidator]]. |
||||
* |
||||
* @see \yii\validators\RequiredValidator |
||||
* @see ValidationAsset |
||||
* |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class RequiredValidator extends ClientValidator |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public function build($validator, $model, $attribute, $view) |
||||
{ |
||||
ValidationAsset::register($view); |
||||
$options = $this->getClientOptions($validator, $model, $attribute); |
||||
return 'yii.validation.required(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');'; |
||||
} |
||||
|
||||
/** |
||||
* Returns the client-side validation options. |
||||
* @param \yii\validators\RequiredValidator $validator the server-side validator. |
||||
* @param \yii\base\Model $model the model being validated |
||||
* @param string $attribute the attribute name being validated |
||||
* @return array the client-side validation options |
||||
*/ |
||||
public function getClientOptions($validator, $model, $attribute) |
||||
{ |
||||
$options = []; |
||||
if ($validator->requiredValue !== null) { |
||||
$options['message'] = $validator->formatMessage($validator->message, [ |
||||
'requiredValue' => $validator->requiredValue, |
||||
]); |
||||
$options['requiredValue'] = $validator->requiredValue; |
||||
} else { |
||||
$options['message'] = $validator->message; |
||||
} |
||||
if ($validator->strict) { |
||||
$options['strict'] = 1; |
||||
} |
||||
|
||||
$options['message'] = $validator->formatMessage($options['message'], [ |
||||
'attribute' => $model->getAttributeLabel($attribute), |
||||
]); |
||||
|
||||
return $options; |
||||
} |
||||
} |
@ -1,78 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery\validators\client; |
||||
|
||||
use yii\jquery\ValidationAsset; |
||||
use yii\validators\client\ClientValidator; |
||||
|
||||
/** |
||||
* StringValidator composes client-side validation code from [[\yii\validators\StringValidator]]. |
||||
* |
||||
* @see \yii\validators\StringValidator |
||||
* @see ValidationAsset |
||||
* |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class StringValidator extends ClientValidator |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public function build($validator, $model, $attribute, $view) |
||||
{ |
||||
ValidationAsset::register($view); |
||||
$options = $this->getClientOptions($validator, $model, $attribute); |
||||
return 'yii.validation.string(value, messages, ' . json_encode($options, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ');'; |
||||
} |
||||
|
||||
/** |
||||
* Returns the client-side validation options. |
||||
* @param \yii\validators\StringValidator $validator the server-side validator. |
||||
* @param \yii\base\Model $model the model being validated |
||||
* @param string $attribute the attribute name being validated |
||||
* @return array the client-side validation options |
||||
*/ |
||||
public function getClientOptions($validator, $model, $attribute) |
||||
{ |
||||
$label = $model->getAttributeLabel($attribute); |
||||
|
||||
$options = [ |
||||
'message' => $validator->formatMessage($validator->message, [ |
||||
'attribute' => $label, |
||||
]), |
||||
]; |
||||
|
||||
if ($validator->min !== null) { |
||||
$options['min'] = $validator->min; |
||||
$options['tooShort'] = $validator->formatMessage($validator->tooShort, [ |
||||
'attribute' => $label, |
||||
'min' => $validator->min, |
||||
]); |
||||
} |
||||
if ($validator->max !== null) { |
||||
$options['max'] = $validator->max; |
||||
$options['tooLong'] = $validator->formatMessage($validator->tooLong, [ |
||||
'attribute' => $label, |
||||
'max' => $validator->max, |
||||
]); |
||||
} |
||||
if ($validator->length !== null) { |
||||
$options['is'] = $validator->length; |
||||
$options['notEqual'] = $validator->formatMessage($validator->notEqual, [ |
||||
'attribute' => $label, |
||||
'length' => $validator->length, |
||||
]); |
||||
} |
||||
if ($validator->skipOnEmpty) { |
||||
$options['skipOnEmpty'] = 1; |
||||
} |
||||
|
||||
return $options; |
||||
} |
||||
} |
@ -1,72 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yii\jquery\validators\client; |
||||
|
||||
use yii\helpers\Json; |
||||
use yii\jquery\PunycodeAsset; |
||||
use yii\jquery\ValidationAsset; |
||||
use yii\validators\client\ClientValidator; |
||||
use yii\web\JsExpression; |
||||
|
||||
/** |
||||
* UrlValidator composes client-side validation code from [[\yii\validators\UrlValidator]]. |
||||
* |
||||
* @see \yii\validators\UrlValidator |
||||
* @see ValidationAsset |
||||
* |
||||
* @author Paul Klimov <klimov.paul@gmail.com> |
||||
* @since 2.1.0 |
||||
*/ |
||||
class UrlValidator extends ClientValidator |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
public function build($validator, $model, $attribute, $view) |
||||
{ |
||||
/* @var $validator \yii\validators\UrlValidator */ |
||||
ValidationAsset::register($view); |
||||
if ($validator->enableIDN) { |
||||
PunycodeAsset::register($view); |
||||
} |
||||
$options = $this->getClientOptions($validator, $model, $attribute); |
||||
return 'yii.validation.url(value, messages, ' . Json::htmlEncode($options) . ');'; |
||||
} |
||||
|
||||
/** |
||||
* Returns the client-side validation options. |
||||
* @param \yii\validators\UrlValidator $validator the server-side validator. |
||||
* @param \yii\base\Model $model the model being validated |
||||
* @param string $attribute the attribute name being validated |
||||
* @return array the client-side validation options |
||||
*/ |
||||
public function getClientOptions($validator, $model, $attribute) |
||||
{ |
||||
if (strpos($validator->pattern, '{schemes}') !== false) { |
||||
$pattern = str_replace('{schemes}', '(' . implode('|', $validator->validSchemes) . ')', $validator->pattern); |
||||
} else { |
||||
$pattern = $validator->pattern; |
||||
} |
||||
|
||||
$options = [ |
||||
'pattern' => new JsExpression($pattern), |
||||
'message' => $validator->formatMessage($validator->message, [ |
||||
'attribute' => $model->getAttributeLabel($attribute), |
||||
]), |
||||
'enableIDN' => (bool) $validator->enableIDN, |
||||
]; |
||||
if ($validator->skipOnEmpty) { |
||||
$options['skipOnEmpty'] = 1; |
||||
} |
||||
if ($validator->defaultScheme !== null) { |
||||
$options['defaultScheme'] = $validator->defaultScheme; |
||||
} |
||||
|
||||
return $options; |
||||
} |
||||
} |
@ -1,225 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yiiunit\framework\jquery; |
||||
|
||||
use Yii; |
||||
use yii\base\DynamicModel; |
||||
use yii\jquery\ActiveFormAsset; |
||||
use yii\jquery\ActiveFormClientScript; |
||||
use yii\web\View; |
||||
use yii\widgets\ActiveField; |
||||
use yii\widgets\ActiveForm; |
||||
use yiiunit\TestCase; |
||||
|
||||
/** |
||||
* @group jquery |
||||
*/ |
||||
class ActiveFormClientScriptTest extends TestCase |
||||
{ |
||||
/** |
||||
* @var ActiveField |
||||
*/ |
||||
private $activeField; |
||||
/** |
||||
* @var DynamicModel |
||||
*/ |
||||
private $helperModel; |
||||
/** |
||||
* @var ActiveForm |
||||
*/ |
||||
private $helperForm; |
||||
/** |
||||
* @var string |
||||
*/ |
||||
private $attributeName = 'attributeName'; |
||||
|
||||
|
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
protected function setUp() |
||||
{ |
||||
parent::setUp(); |
||||
// dirty way to have Request object not throwing exception when running testHomeLinkNull() |
||||
$_SERVER['SCRIPT_FILENAME'] = "index.php"; |
||||
$_SERVER['SCRIPT_NAME'] = "index.php"; |
||||
|
||||
$this->mockWebApplication([ |
||||
'components' => [ |
||||
'assetManager' => [ |
||||
'basePath' => '@testWebRoot/assets', |
||||
'baseUrl' => '@testWeb/assets', |
||||
'bundles' => [ |
||||
ActiveFormAsset::class => [ |
||||
'sourcePath' => null, |
||||
'basePath' => null, |
||||
'baseUrl' => 'http://example.com/assets', |
||||
'depends' => [], |
||||
], |
||||
], |
||||
], |
||||
], |
||||
]); |
||||
|
||||
Yii::setAlias('@testWeb', '/'); |
||||
Yii::setAlias('@testWebRoot', '@yiiunit/data/web'); |
||||
|
||||
$this->helperModel = new DynamicModel(['attributeName']); |
||||
ob_start(); |
||||
$this->helperForm = ActiveForm::begin([ |
||||
'action' => '/something', |
||||
'as clientScript' => ActiveFormClientScript::class |
||||
]); |
||||
ActiveForm::end(); |
||||
ob_end_clean(); |
||||
|
||||
$this->activeField = new ActiveField(); |
||||
$this->activeField->form = $this->helperForm; |
||||
$this->activeField->model = $this->helperModel; |
||||
$this->activeField->attribute = $this->attributeName; |
||||
} |
||||
|
||||
/** |
||||
* @return array client options of current [[activeField]] instance. |
||||
*/ |
||||
protected function getActiveFieldClientOptions() |
||||
{ |
||||
// invoke protected method : |
||||
return $this->invokeMethod($this->activeField->form->getBehavior('clientScript'), 'getFieldClientOptions', [$this->activeField]); |
||||
} |
||||
|
||||
// Tests : |
||||
|
||||
public function testRegisterClientScript() |
||||
{ |
||||
$model = new DynamicModel(['name']); |
||||
$model->addRule(['name'], 'required'); |
||||
|
||||
$mockedView = $this->createMock(View::class); |
||||
$mockedView |
||||
->expects($this->once()) |
||||
->method('registerJs') |
||||
->with($this->matches("jQuery('#test-form').yiiActiveForm([], {\"validateOnSubmit\":false});")); |
||||
$mockedView |
||||
->expects($this->once()) |
||||
->method('registerAssetBundle') |
||||
->willReturn(true); |
||||
|
||||
ob_start(); |
||||
ob_implicit_flush(false); |
||||
|
||||
$form = ActiveForm::begin([ |
||||
'id' => 'test-form', |
||||
'action' => '/something', |
||||
'view' => $mockedView, |
||||
'validateOnSubmit' => false, |
||||
'as clientScript' => ActiveFormClientScript::class, |
||||
]); |
||||
$form->field($model, 'name'); |
||||
$form::end(); |
||||
|
||||
ob_get_clean(); |
||||
} |
||||
|
||||
public function testGetClientOptionsWithActiveAttributeInScenario() |
||||
{ |
||||
$this->activeField->model->addRule($this->attributeName, TestValidator::class); |
||||
$this->activeField->form->enableClientValidation = false; |
||||
|
||||
// expected empty |
||||
$actualValue = $this->getActiveFieldClientOptions(); |
||||
$this->assertEmpty($actualValue); |
||||
|
||||
} |
||||
|
||||
public function testGetClientOptionsClientValidation() |
||||
{ |
||||
$this->activeField->model->addRule($this->attributeName, TestValidator::class); |
||||
$this->activeField->enableClientValidation = true; |
||||
$actualValue = $this->getActiveFieldClientOptions(); |
||||
$expectedJsExpression = "function (attribute, value, messages, deferred, \$form) {return true;}"; |
||||
$this->assertEquals($expectedJsExpression, $actualValue['validate']); |
||||
|
||||
$this->assertTrue(!isset($actualValue['validateOnChange'])); |
||||
$this->assertTrue(!isset($actualValue['validateOnBlur'])); |
||||
$this->assertTrue(!isset($actualValue['validateOnType'])); |
||||
$this->assertTrue(!isset($actualValue['validationDelay'])); |
||||
$this->assertTrue(!isset($actualValue['enableAjaxValidation'])); |
||||
|
||||
$this->activeField->validateOnChange = $expectedValidateOnChange = false; |
||||
$this->activeField->validateOnBlur = $expectedValidateOnBlur = false; |
||||
$this->activeField->validateOnType = $expectedValidateOnType = true; |
||||
$this->activeField->validationDelay = $expectedValidationDelay = 100; |
||||
$this->activeField->enableAjaxValidation = $expectedEnableAjaxValidation = true; |
||||
|
||||
$actualValue = $this->getActiveFieldClientOptions(); |
||||
|
||||
$this->assertTrue($expectedValidateOnChange === $actualValue['validateOnChange']); |
||||
$this->assertTrue($expectedValidateOnBlur === $actualValue['validateOnBlur']); |
||||
$this->assertTrue($expectedValidateOnType === $actualValue['validateOnType']); |
||||
$this->assertTrue($expectedValidationDelay === $actualValue['validationDelay']); |
||||
$this->assertTrue($expectedEnableAjaxValidation === $actualValue['enableAjaxValidation']); |
||||
} |
||||
|
||||
public function testGetClientOptionsValidatorWhenClientSet() |
||||
{ |
||||
$this->activeField->enableAjaxValidation = true; |
||||
$this->activeField->model->addRule($this->attributeName, TestValidator::class); |
||||
|
||||
foreach($this->activeField->model->validators as $validator) { |
||||
$validator->whenClient = "function (attribute, value) { return 'yii2' == 'yii2'; }"; // js |
||||
} |
||||
|
||||
$actualValue = $this->getActiveFieldClientOptions(); |
||||
$expectedJsExpression = "function (attribute, value, messages, deferred, \$form) {if ((function (attribute, value) " |
||||
. "{ return 'yii2' == 'yii2'; })(attribute, value)) { return true; }}"; |
||||
|
||||
$this->assertEquals($expectedJsExpression, $actualValue['validate']->expression); |
||||
} |
||||
|
||||
/** |
||||
* @link https://github.com/yiisoft/yii2/issues/7627 |
||||
*/ |
||||
public function testGetClientOptionsWithCustomInputId() |
||||
{ |
||||
$this->activeField->model->addRule($this->attributeName, TestValidator::class); |
||||
$this->activeField->inputOptions['id'] = 'custom-input-id'; |
||||
$this->activeField->textInput(); |
||||
$actualValue = $this->getActiveFieldClientOptions(); |
||||
|
||||
$this->assertArraySubset([ |
||||
'id' => 'dynamicmodel-attributename', |
||||
'name' => $this->attributeName, |
||||
'container' => '.field-custom-input-id', |
||||
'input' => '#custom-input-id', |
||||
], $actualValue); |
||||
|
||||
$this->activeField->textInput(['id' => 'custom-textinput-id']); |
||||
$actualValue = $this->getActiveFieldClientOptions(); |
||||
|
||||
$this->assertArraySubset([ |
||||
'id' => 'dynamicmodel-attributename', |
||||
'name' => $this->attributeName, |
||||
'container' => '.field-custom-textinput-id', |
||||
'input' => '#custom-textinput-id', |
||||
], $actualValue); |
||||
} |
||||
} |
||||
|
||||
class TestValidator extends \yii\validators\Validator |
||||
{ |
||||
public function clientValidateAttribute($object, $attribute, $view) |
||||
{ |
||||
return "return true;"; |
||||
} |
||||
|
||||
public function setWhenClient($js) |
||||
{ |
||||
$this->whenClient = $js; |
||||
} |
||||
} |
@ -1,78 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yiiunit\framework\jquery; |
||||
|
||||
use Yii; |
||||
use yii\data\ArrayDataProvider; |
||||
use yii\grid\GridView; |
||||
use yii\jquery\GridViewAsset; |
||||
use yii\jquery\GridViewClientScript; |
||||
use yii\web\View; |
||||
use yiiunit\TestCase; |
||||
|
||||
/** |
||||
* @group jquery |
||||
*/ |
||||
class GridViewClientScriptTest extends TestCase |
||||
{ |
||||
/** |
||||
* {@inheritdoc} |
||||
*/ |
||||
protected function setUp() |
||||
{ |
||||
parent::setUp(); |
||||
// dirty way to have Request object not throwing exception when running testHomeLinkNull() |
||||
$_SERVER['SCRIPT_FILENAME'] = "index.php"; |
||||
$_SERVER['SCRIPT_NAME'] = "index.php"; |
||||
|
||||
$this->mockWebApplication([ |
||||
'components' => [ |
||||
'assetManager' => [ |
||||
'basePath' => '@testWebRoot/assets', |
||||
'baseUrl' => '@testWeb/assets', |
||||
'bundles' => [ |
||||
GridViewAsset::class => [ |
||||
'sourcePath' => null, |
||||
'basePath' => null, |
||||
'baseUrl' => 'http://example.com/assets', |
||||
'depends' => [], |
||||
], |
||||
], |
||||
], |
||||
], |
||||
]); |
||||
|
||||
Yii::setAlias('@testWeb', '/'); |
||||
Yii::setAlias('@testWebRoot', '@yiiunit/data/web'); |
||||
} |
||||
|
||||
public function testRegisterClientScript() |
||||
{ |
||||
$row = ['id' => 1, 'name' => 'Name1', 'value' => 'Value1', 'description' => 'Description1',]; |
||||
|
||||
GridView::widget([ |
||||
'id' => 'test-grid', |
||||
'dataProvider' => new ArrayDataProvider( |
||||
[ |
||||
'allModels' => [ |
||||
$row, |
||||
], |
||||
] |
||||
), |
||||
'filterUrl' => 'http://example.com/filter', |
||||
'as clientScript' => [ |
||||
'class' => GridViewClientScript::class |
||||
], |
||||
]); |
||||
|
||||
$this->assertTrue(Yii::$app->assetManager->bundles[GridViewAsset::class] instanceof GridViewAsset); |
||||
$this->assertNotEmpty(Yii::$app->view->js[View::POS_END]); |
||||
$js = reset(Yii::$app->view->js[View::POS_END]); |
||||
$this->assertContains("jQuery('#test-grid').yiiGridView(", $js); |
||||
} |
||||
} |
@ -1,49 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yiiunit\framework\jquery\validators; |
||||
|
||||
use yii\jquery\validators\client\BooleanValidator; |
||||
use yii\web\View; |
||||
use yiiunit\data\validators\models\FakedValidationModel; |
||||
use yiiunit\TestCase; |
||||
|
||||
/** |
||||
* @group jquery |
||||
* @group validators |
||||
*/ |
||||
class BooleanValidatorTest extends TestCase |
||||
{ |
||||
public function testBuild() |
||||
{ |
||||
$validator = new \yii\validators\BooleanValidator([ |
||||
'trueValue' => true, |
||||
'falseValue' => false, |
||||
'strict' => true, |
||||
]); |
||||
|
||||
$clientValidator = new BooleanValidator(); |
||||
|
||||
$model = new FakedValidationModel(); |
||||
$model->attrA = true; |
||||
$model->attrB = '1'; |
||||
$model->attrC = '0'; |
||||
$model->attrD = []; |
||||
|
||||
$this->assertEquals( |
||||
'yii.validation.boolean(value, messages, {"trueValue":true,"falseValue":false,"message":"attrB must be either \"true\" or \"false\".","skipOnEmpty":1,"strict":1});', |
||||
$clientValidator->build($validator, $model, 'attrB', new ViewStub()) |
||||
); |
||||
} |
||||
} |
||||
|
||||
class ViewStub extends View |
||||
{ |
||||
public function registerAssetBundle($name, $position = null) |
||||
{ |
||||
} |
||||
} |
@ -1,78 +0,0 @@
|
||||
<?php |
||||
/** |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
namespace yiiunit\framework\jquery\validators; |
||||
|
||||
use yii\jquery\validators\client\NumberValidator; |
||||
use yii\web\View; |
||||
use yiiunit\data\validators\models\FakedValidationModel; |
||||
use yiiunit\TestCase; |
||||
|
||||
/** |
||||
* @group jquery |
||||
* @group validators |
||||
*/ |
||||
class NumberValidatorTest extends TestCase |
||||
{ |
||||
/** |
||||
* @see https://github.com/yiisoft/yii2/issues/3118 |
||||
*/ |
||||
public function testBuild() |
||||
{ |
||||
$view = new View(['assetBundles' => ['yii\jquery\ValidationAsset' => true]]); |
||||
$clientValidator = new NumberValidator(); |
||||
$model = new FakedValidationModel(); |
||||
|
||||
$js = $clientValidator->build( |
||||
new \yii\validators\NumberValidator([ |
||||
'min' => 5, |
||||
'max' => 10, |
||||
]), |
||||
$model, |
||||
'attr_number', |
||||
$view |
||||
); |
||||
$this->assertContains('"min":5', $js); |
||||
$this->assertContains('"max":10', $js); |
||||
|
||||
$js = $clientValidator->build( |
||||
new \yii\validators\NumberValidator([ |
||||
'min' => '5', |
||||
'max' => '10', |
||||
]), |
||||
$model, |
||||
'attr_number', |
||||
$view |
||||
); |
||||
$this->assertContains('"min":5', $js); |
||||
$this->assertContains('"max":10', $js); |
||||
|
||||
$js = $clientValidator->build( |
||||
new \yii\validators\NumberValidator([ |
||||
'min' => 5.65, |
||||
'max' => 13.37, |
||||
]), |
||||
$model, |
||||
'attr_number', |
||||
$view |
||||
); |
||||
$this->assertContains('"min":5.65', $js); |
||||
$this->assertContains('"max":13.37', $js); |
||||
|
||||
$js = $clientValidator->build( |
||||
new \yii\validators\NumberValidator([ |
||||
'min' => '5.65', |
||||
'max' => '13.37', |
||||
]), |
||||
$model, |
||||
'attr_number', |
||||
$view |
||||
); |
||||
$this->assertContains('"min":5.65', $js); |
||||
$this->assertContains('"max":13.37', $js); |
||||
} |
||||
} |
Loading…
Reference in new issue