Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.8k views
in Technique[技术] by (71.8m points)

javascript - Validate selection of at least one checkbox using model rules. Yii2

I am using the following code to validate that I have at least one checkbox selected but I have a problem.

JS

$("#btn_enviar").click(function() {

    var invalido = 0;
    $(".item").each(function( ) {
       if ($(this).find("select").val() == 1) {
         var cont = 0;
         $(this).find("input:checkbox, input:radio").each(function() {

              if($(this).is(":checked")){
                  cont++;
              }

         });
       }
       if(cont < 1){
           $(this).find(".text-error-check").show();
           $(this).find(".dynamicform_inner").css({
              "border": "2px solid #dd4b39",
              "background-color": "white"
            });

            invalido = 1;
        }
    });

}); ');

For example, if I send the data first without having a selected checkbox it works for me but it ignores the other validations of the rules and I only get the selection error, if I then select a checkbox and send the data again, the validations of the rules of the model work.

First send

enter image description here

Second send

enter image description here

I have tried to do it with the rules in my model but have not been successful. How can I include it together with the other rules of the model?

P.D: I am using the dynamic form to generate the checkboxes and inputs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would do it this way:

Model rules

public function rules()
    {
        return [
            // an inline validator defined as the model method checkSelection()
            ['checkboxes', 'checkSelection'],
        ...
        ];
    }

public function checkSelection($attribute, $params, $validator)
{
    $error = true;
    foreach ($this->checkboxes as $checkbox) {
        //if at least 1 checkbox is checked then we skip error.
        if ($checkbox) {
            $error = false;
        }
    }
    if ($error) {
        $this->addError('checkboxes', 'You must select at least one checkbox to continue');
    }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...