簡體   English   中英

自定義驗證器中的Parsley.js動態消息

[英]Parsley.js Dynamic messages in custom validator

我正在使用自定義驗證程序來檢查出生日期,到目前為止,它幾乎沒有任何內容,但是我嘗試根據錯誤添加動態消息,並且對我不起作用,它會顯示帶有空白消息的容器,有任何想法嗎?

這是自定義驗證器的代碼:

window.Parsley.addValidator('age', {
            validate: function(value, id){
                switch(id){
                    case 'main':
                        var day = $('#birthdate_day').val();
                        var month = $('#birthdate_month').val();
                        var year = $('#birthdate_year').val();
                        if(!day || !month || !year){

                            window.Parsley.addMessage('en', 'age','Error1 ');

                            return false;
                        } else {
                            window.Parsley.addMessage('en', 'age','Error 2');
                        }
                    break;
                }
                return true;
            },
            messages: {
                en: 'Default error',
            }
        });

我嘗試過的另一件事是在驗證執行期間設置data-parsley-age-message =“ error”,但是它僅在第二次運行驗證時顯示錯誤。

提前致謝。

編輯1:

 window.Parsley.addValidator('age', {
            validate: function(value, id){
                $('.birthdate_container').find('ul').remove();
                switch(id){
                    case 'main':
                        var day = $('#birthdate_day').val();
                        var month = $('#birthdate_month').val();
                        var year = $('#birthdate_year').val();
                        if(!day || !month || !year){
                            return $.Deferred().reject("One of them is blank");
                        } else if(day > 2 || month > 2 || year < 2016){
                            return $.Deferred().reject("Else test of another message");
                        } else {
                            return true;
                        }
                    break;
                }
                return true;
            },
        });

一個更簡潔的解決方案(別介意,它只是用於測試),但是由於我不知道如何在返回true時更新3個元素的類,因此仍然無法使它起作用。

編輯2:

但是,僅使用jQuery處理類工作即可,因為我需要刪除ul(否則消息將堆棧並且我不希望這樣),每當發生錯誤並在其中出現另一個錯誤后觸發該錯誤時,它就會將其刪除。

window.Parsley.addValidator('age', {
            validate: function(value, id){
                $('.birthdate_container').find('ul').remove();
                switch(id){
                    case 'main':
                        var day = $('#birthdate_day').val();
                        var month = $('#birthdate_month').val();
                        var year = $('#birthdate_year').val();
                        if(!day || !month || !year){
                            $('.birthdate_container').find('.parsley-success').removeClass('parsley-success').addClass('parsley-error');
                            return $.Deferred().reject("Un campo es blanco");
                        } else if(day > 2 || month > 2 || year < 2016){
                            $('.birthdate_container').find('.parsley-success').removeClass('parsley-success').addClass('parsley-error');
                            return $.Deferred().reject("dia > 2 o mes > 2 o años < 2016");
                        } else {
                            $('.birthdate_container').find('.parsley-error').removeClass('parsley-error').addClass('parsley-success');
                            return true;
                        }
                    break;
                }
                return true;
            },
        });

它的文檔記錄不充分,但是您可以通過返回被拒絕的承諾從驗證器返回錯誤消息。 檢查此示例

經過大量修改后,我想我明白了,我必須重置所有以前的歐芹,以便即使需要時也可以重寫該消息(即使是相同的消息)

window.Parsley.addValidator('age', {
            validate: function(value, id){
                switch(id){
                    case 'main':
                        var container = $('.birthdate_container');
                        container.find('ul').remove();
                        var day = $('#birthdate_day');
                        day.parsley().reset();
                        var month = $('#birthdate_month');
                        month.parsley().reset();
                        var year = $('#birthdate_year');
                        year.parsley().reset();

                        if(day.val() === '' || month.val() === '' || year.val() === ''){
                            container.find('.dropdown').removeClass('parsley-success').addClass('parsley-error');
                            return $.Deferred().reject("Un campo es blanco");
                        } else if(day.val() > 2 || month.val() > 2 || year.val() < 2016){
                            container.find('.dropdown').removeClass('parsley-success').addClass('parsley-error');
                            return $.Deferred().reject("dia > 2 o mes > 2 o años < 2016");
                        } else {
                            container.find('.dropdown').removeClass('parsley-error').addClass('parsley-success');
                            return true;
                        }
                    break;
                }
                return true;
            }
        });

PD:同樣,第二個就是測試您是否可以拋出不同的消息。 驗證本身是不相關的。

我的最終作品:

window.Parsley.addValidator('age', {
            validate: function(value, id, instance){
                var container = instance.$element.closest('.form-item');
                container.find('ul').remove();
                var msg = '';
                var day = container.find('select').filter(function() {return this.id.match(/\w*birthdate_day/);});
                var month = container.find('select').filter(function() {return this.id.match(/\w*birthdate_month/);});
                var year = container.find('select').filter(function() {return this.id.match(/\w*birthdate_year/);});
                day.parsley().reset();
                month.parsley().reset();
                year.parsley().reset();
                var helpContainer = '<ul class="parsley-errors-list filled"><li class="parsley-age"></li></ul>';

                if(value === ''){
                    container.find('select').parent().addClass('parsley-error');
                    msg = "This field is required";

                }
                /* Take several notes here
                1) I wrap my select in a div, for stylying purposes, so I check the default placeholder, when something is selected
                    this placeholder is changed with the value of the select (this is not shown here, it's done elsewhere)
                2) I use DD - MM - YYYY as placeholders, if any of these place holders are already showing in the div,
                    then I don't validate them because they are still 'clean'
                3) If the user clicks the submit button though, I set a js variable with this action and then validate the value anyways
                    because I don't allow blank dates, however, I can't use the parsley-required feature as it messes up my validation
                */
                else if(obj.action !== 'submit' && (day.parent().attr('data-placeholder') === 'DD' ||
                    month.parent().attr('data-placeholder') === 'MM' ||
                    year.parent().attr('data-placeholder') === 'YYYY'))
                {
                    container.find('select').parent().removeClass('parsley-error')
                    container.find('select').filter(function(){ return this.value}).parent().addClass('parsley-success');
                    return true;
                }
                else if(day.val() === '' || month.val() === '' || year.val() === '') {
                    container.find('select').parent().addClass('parsley-error');
                    msg = "This field is required";
                }
                /*
                I have another validation process past this point that uses a different error, but I'll point out the very basic
                which is just make some other validation and fill the message you want to display.

                Let's assume you want the person not to be underage and you control that in your form somehow
                */
                else if (!underageAllowed){
                    var bdate =  String("00" + day.val()).slice(-2) + "/" + String("00" + month.val()).slice(-2) + "/" + year.val();
                    var tdate = moment(); // Today
                    bdate = moment(bdate,'DD/MM/YYYY');
                    var age = tdate.diff(bdate, 'years');
                    if(age < 18){
                        container.find('select').parent().addClass('parsley-error');
                        msg = "Only people with over 18 years old are allower";
                    }
                }                   

                if(msg !== ''){
                    if(obj.action === 'submit'){
                        container.append(helpContainer);
                        container.find('.parsley-age').html(msg)
                    }
                    return $.Deferred().reject(msg);
                } else {
                    container.find('select').filter(function(){ return this.value}).parent().addClass('parsley-success');
                    return true;
                }
            },
        });

然后,我將驗證器分配給每個具有“ birthdate_”作為ID的字段(birthdate_day,birthatedate_month和birthdate_year)

    $("[id^='birthdate_']").attr('data-parsley-age','true')
            .attr('data-parsley-trigger', "change")
            .attr('data-parsley-validate-if-empty', "true");

每個字段正確的errorContainer

$('#main_form').parsley({
            errorsContainer: function(el){
                if(el.$element.is('[data-parsley-age]'))
                    return el.$element.closest('.form-item');
            },

最后是我的html布局

<div class="form-item">
<label>Date of birth</label>
<div class="dropdown" data-placeholder="DD">
    <select id="birthdate_day" name="birthdate_day">
        <option value="">-</option> //If user selects this, the validation throws error for all the fields
        //Options 1 through 31
    </select>
</div>
<div class="dropdown" data-placeholder="MM">
    <select id="birthdate_month" name="birthdate_month">
        <option value="">-</option>  //If user selects this, the validation throws error for all the fields
        //Options 1 through 12
    </select>
</div>
<div class="dropdown" data-placeholder="YYY">
    <select id="birthdate_year" name="birthdate_year">
        <option value="">-</option> //If user selects this, the validation throws error for all the fields
        //Options 1 through 12
    </select>
</div>

希望這對任何人有幫助,我花了一些時間來解決所有這些問題。

如果只想處理動態消息,則不要在message對象中,而在驗證方法中包括消息文本:

instance.addError('en', {message: 'Hello World'});

就這么簡單。 只需閱讀帶注釋的源代碼,它將揭示許多簡單功能。

編輯:實際上,我只是注意到您確實需要某些東西,否則它會拋出自己的錯誤消息,因此您可以使用以下方法解決此問題:

messages: {
    en: '...'
}

我剛剛測試過,效果很好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM