code

jquery 유효성 검사 적어도 하나의 확인란

codestyles 2020. 12. 28. 08:10
반응형

jquery 유효성 검사 적어도 하나의 확인란


다음과 같은 것이 있습니다.

<form>
<input name='roles' type='checkbox' value='1' />
<input name='roles' type='checkbox' value='2' />
<input name='roles' type='checkbox' value='3' />
<input name='roles' type='checkbox' value='4' />
<input name='roles' type='checkbox' value='5' />
<input type='submit' value='submit' />
<form>

적어도 하나의 확인란 (역할)을 선택해야하는지 확인하고 싶습니다. jquery.validate로 가능합니까?


유효성 검사 플러그인은 현재 / 중점 요소 만 확인하므로 모든 확인란의 유효성을 검사하기 위해 유효성 검사기에 사용자 지정 규칙을 추가해야합니다. 위의 답변과 유사합니다.

$.validator.addMethod("roles", function(value, elem, param) {
   return $(".roles:checkbox:checked").length > 0;
},"You must select at least one!");

그리고 요소 :

<input class='{roles: true}' name='roles' type='checkbox' value='1' />

또한 오류 메시지 표시가 충분하지 않을 수 있습니다. 하나의 확인란 만 강조 표시되고 하나의 메시지 만 표시됩니다. 다른 별도의 확인란을 클릭 한 다음 두 번째 확인란에 대해 유효 함을 반환하는 경우 원본은 여전히 ​​유효하지 않은 것으로 표시되고 양식이 유효하더라도 오류 메시지가 계속 표시됩니다. 나는 항상이 경우 오류를 직접 표시하고 숨기는 데 의지 해 왔으며 유효성 검사기는 양식을 제출하지 않는 것만 처리합니다.

다른 옵션은 확인란을 클릭하여 숨겨진 입력 값을 "유효"로 변경하는 함수를 작성한 다음 숨겨진 요소에 유효성 검사 규칙을 연결하는 것입니다. 이것은 onSubmit 이벤트에서만 유효성을 검사하지만 적절한 시간에 메시지를 표시하고 숨 깁니다. 이것들은 validate 플러그인과 함께 사용할 수있는 유일한 옵션에 관한 것입니다.

도움이 되었기를 바랍니다.


https://github.com/ffmike/jquery-validate의

 <label for="spam_email">
     <input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" validate="required:true, minlength:2" /> Spam via E-Mail </label>
 <label for="spam_phone">
     <input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" /> Spam via Phone </label>
 <label for="spam_mail">
     <input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" /> Spam via Mail </label>
 <label for="spam[]" class="error">Please select at least two types of spam.</label>

자바 스크립트 만 사용하는 태그에서 "유효성 검사"필드 없이도 동일합니다.

$("#testform").validate({ 
    rules: { 
            "spam[]": { 
                    required: true, 
                    minlength: 1 
            } 
    }, 
    messages: { 
            "spam[]": "Please select at least two types of spam."
    } 
}); 

입력에 다른 이름이 필요한 경우 다음과 같이 somethig를 사용할 수 있습니다.

<input type="hidden" name="spam" id="spam"/>
<label for="spam_phone">
    <input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam_phone" /> Spam via Phone</label>
<label for="spam_mail">
    <input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam_mail" /> Spam via Mail </label>

자바 스크립트 :

 $("#testform").validate({ 
    rules: { 
        spam: { 
            required: function (element) {
                var boxes = $('.checkbox');
                if (boxes.filter(':checked').length == 0) {
                    return true;
                }
                return false;
            },
            minlength: 1 
        } 
    }, 
    messages: { 
            spam: "Please select at least two types of spam."
    } 
}); 

입력 전에 숨겨진 입력을 추가하고 선택한 확인란이없는 경우 "필수"로 설정했습니다.


음 먼저 귀하의 ID 속성은 고유해야합니다. 귀하의 코드는

<form>
<input class='roles' name='roles' type='checkbox' value='1' />
<input class='roles' name='roles' type='checkbox' value='2' />
<input class='roles' name='roles' type='checkbox' value='3' />
<input class='roles' name='roles' type='checkbox' value='4' />
<input class='roles' name='roles' type='checkbox' value='5' />
<input type='submit' value='submit' />
</form>

귀하의 문제에 대해 :

if($('.roles:checkbox:checked').length == 0)
  // no checkbox checked, do something...
else
  // at least one checkbox checked...

BUT, remember that a JavaScript form validation is only indicative, all validations MUST be done server-side.


$("#idform").validate({
    rules: {            
        'roles': {
            required: true,
        },
    },
    messages: {            
        'roles': {
            required: "One Option please",
        },
    }
});

This is how I have dealt with it in the past:

$().ready(function() {                                                      
    $("#contact").validate({
        submitHandler: function(form) {
            // see if selectone is even being used
            var boxes = $('.selectone:checkbox');
            if(boxes.length > 0) {
                if( $('.selectone:checkbox:checked').length < 1) {
                    alert('Please select at least one checkbox');
                    boxes[0].focus();
                    return false;
                }
            }
            form.submit();
        }
    }); 

});

It's highly probable that you want to have a text next to the checkbox. In that case, you can put the checkbox inside a label like I do below:

<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="72" aria-required="true" class="error"> All Over</label>
<label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="73" aria-required="true" class="error"> All Over X2</label>

The problem is that when the error message is displayed, it's going to be inserted after the checkbox but before the text, making it unreadable. In order to fix that, I changed the error placement function:

if (element.is(":checkbox")) {
    error.insertAfter(element.parent().parent());
}
else {
    error.insertAfter(element);
}

It depends on your layout but what I did is to have a special error placement for checkbox controls. I get the parent of the checkbox, which is a label, and then I get the parent of it, which is a div in my case. This way, the error is placed below the list of checkbox controls.


sir_neanderthal has already posted a nice answer.

I just want to point out that if you would like to use different names for your inputs you can also use (or just copy the method) require_from_group method from official jQuery Validation additional-methods.js (link to CDN for version 1.13.1).


make sure the input-name[] is in inverted commas in the ruleset. Took me hours to figure that part out.

$('#testform').validate({
  rules : {
    "name[]": { required: true, minlength: 1 }
  }
});

read more here... http://docs.jquery.com/Plugins/Valid...ets.2C_dots.29

ReferenceURL : https://stackoverflow.com/questions/3035634/jquery-validate-check-at-least-one-checkbox

반응형