yiisoft / yii2

Yii 2: The Fast, Secure and Professional PHP Framework
http://www.yiiframework.com
BSD 3-Clause "New" or "Revised" License
14.24k stars 6.91k forks source link

Limit the number of elements to 1 in initialization in yii.captcha.js #13165

Closed arogachev closed 7 years ago

arogachev commented 7 years ago

Currently it's possible to use multiple elements when initializing captcha.

For example, we can have the following HTML:

<img id="captcha" class="captcha" src="/site/captcha/">
<img id="captcha-2" class="captcha" src="/site/captcha/">

and initialize jQuery plugin like this:

$('.captcha').yiiCaptcha({
    refreshUrl: '/site/captcha?refresh=1',
    hashKey: 'yiiCaptcha/site/captcha'
});

But what's the point of it? Both images will have the same exact settings and click will generate the same exact requests.

I can't think of a use case when multiple captchas with the same settings are needed at one page.

Moreover, I can't remember the case when at least 2 captchas with different settings are used at one page. But if we anyway need different settings, we can initialize it from different elements:

$('#captcha').yiiCaptcha({
    refreshUrl: '/site/captcha?refresh=1',
    hashKey: 'yiiCaptcha/site/captcha'
});

$('#captcha-2').yiiCaptcha({
    refreshUrl: '/posts/captcha?refresh=1',
    hashKey: 'yiiCaptcha/posts/captcha'
});

So I suggest to add an according check in init:

if (this.length > 1) {
    $.error("Captcha can't be initialized for multiple images at the same time.");
}

Then we can get rid of the loop used in init:

init: function (options) {
    return this.each(function () {
        var $e = $(this);
        var settings = $.extend({}, defaults, options || {});
        $e.data('yiiCaptcha', {
            settings: settings
        });

        $e.on('click.yiiCaptcha', function () {
            methods.refresh.apply($e);
            return false;
        });
    });
},
SilverFire commented 7 years ago

Don't have any objections. Could be a minor BC break though

samdark commented 7 years ago

What if there are two forms at the same page: login form and signup form. Both have a captcha. In this case it may be identical but still it's two captcha inputs.

arogachev commented 7 years ago

@samdark Agree. Better leave it as is in this case.