developer tip

jQuery 재정의 기본 유효성 검사 오류 메시지 표시 (Css) Popup / Tooltip like

optionbox 2020. 11. 3. 07:57
반응형

jQuery 재정의 기본 유효성 검사 오류 메시지 표시 (Css) Popup / Tooltip like


레이블 대신 div를 사용하여 기본 오류 메시지 레이블을 오버라이드하려고합니다. 이 게시물살펴보고 방법을 얻었지만 CSS에 대한 나의 한계가 나를 괴롭 히고 있습니다. 다음 예제와 같이 어떻게 표시 할 수 있습니까?

예제 # 1 (Dojo) -오류 표시를 보려면 잘못된 입력을 입력해야합니다.
예제 # 2

다음은 오류 레이블을 div 요소로 재정의하는 몇 가지 예제 코드입니다.

$(document).ready(function(){
            $("#myForm").validate({
                rules: {
                    "elem.1": {
                        required: true,
                        digits: true
                    },
                    "elem.2": {
                        required: true
                    }
                },
                errorElement: "div"
            });                  
        });

이제 나는 CSS 부분에서 손실을 입었지만 여기에 있습니다.

div.error {
        position:absolute;
        margin-top:-21px;
     margin-left:150px;
     border:2px solid #C0C097;
        background-color:#fff;
        color:white;
        padding:3px;
        text-align:left;
        z-index:1;
        color:#333333;
     font:100% arial,helvetica,clean,sans-serif;
     font-size:15px;
     font-weight:bold;  
    }

최신 정보:

좋아, 지금이 코드를 사용하고 있지만 이미지와 팝업의 위치가 테두리보다 큽니다. 높이가 동적으로 조정될 수 있습니까?

if (element.attr('type') == 'radio' || element.attr('type') == 'checkbox') {
   element = element.parent();

   offset = element.offset();
   error.insertBefore(element)
   error.addClass('message');  // add a class to the wrapper
   error.css('position', 'absolute');
   error.css('left', offset.left + element.outerWidth());
   error.css('top', offset.top - (element.height() / 2)); // Not working for Radio, displays towards the bottom of the element. also need to test with checkbox
} else {
   // Error placement for single elements
   offset = element.offset();
   error.insertBefore(element)
   error.addClass('message');  // add a class to the wrapper
   error.css('position', 'absolute');
   error.css('left', offset.left + element.outerWidth());
   error.css('top', offset.top - (element.height() / 2));
}

CSS는 아래와 같습니다 (귀하의 CSS 코드).

HTML

<span>
<input type="radio" class="checkbox" value="P" id="radio_P" name="radio_group_name"/>
<label for="radio_P">P</label>
<input type="radio" class="checkbox" value="S" id="radio_S" name="radio_group_name"/>
<label for="radio_S">S</label>
</span>

errorPlacement 옵션을 사용하여 약간의 CSS로 오류 메시지 표시를 대체 할 수 있습니다 . CSS만으로는 필요한 효과를 내기에 충분하지 않기 때문입니다.

$(document).ready(function(){
    $("#myForm").validate({
        rules: {
            "elem.1": {
                required: true,
                digits: true
            },
            "elem.2": {
                required: true
            }
        },
        errorElement: "div",
        wrapper: "div",  // a wrapper around the error message
        errorPlacement: function(error, element) {
            offset = element.offset();
            error.insertBefore(element)
            error.addClass('message');  // add a class to the wrapper
            error.css('position', 'absolute');
            error.css('left', offset.left + element.outerWidth());
            error.css('top', offset.top);
        }

    });
});

왼쪽 및 상단 CSS 속성을 사용하여 요소의 상단, 왼쪽, 오른쪽 또는 하단에 오류 메시지를 표시 할 수 있습니다. 예를 들어 상단에 오류를 표시하려면 :

    errorPlacement: function(error, element) {
        element.before(error);
        offset = element.offset();
        error.css('left', offset.left);
        error.css('top', offset.top - element.outerHeight());
    }

등등. 더 많은 옵션 은 CSS에 대한 jQuery 문서를 참조하십시오 .

다음은 내가 사용한 CSS입니다. 결과는 원하는 것과 똑같습니다. 가능한 한 적은 CSS로 :

div.message{
    background: transparent url(msg_arrow.gif) no-repeat scroll left center;
    padding-left: 7px;
}

div.error{
    background-color:#F3E6E6;
    border-color: #924949;
    border-style: solid solid solid none;
    border-width: 2px;
    padding: 5px;
}

다음은 필요한 배경 이미지입니다.

대체 텍스트
(출처 : scriptiny.com )

옵션 또는 필드 그룹 뒤에 오류 메시지를 표시하려는 경우. 그런 다음 하나의 컨테이너에있는 모든 요소를 ​​'div'또는 'fieldset'으로 그룹화합니다. 예를 들어 모든 '그룹'에 특수 클래스를 추가하십시오. 그리고 errorPlacement 함수의 시작 부분에 다음을 추가합니다.

errorPlacement: function(error, element) {
    if (element.hasClass('group')){
        element = element.parent();
    }
    ...// continue as previously explained

특정 케이스 만 처리하려면 대신 attr을 사용할 수 있습니다.

if (element.attr('type') == 'radio'){
    element = element.parent();
}

이는 상위 요소 옆에 오류 메시지가 표시되기에 충분합니다.

상위 요소의 너비를 100 % 미만으로 변경해야 할 수 있습니다.


나는 당신의 코드를 시도했고 그것은 나를 위해 완벽하게 잘 작동합니다. 다음은 미리보기입니다.대체 텍스트

줄에 맞추기 위해 메시지 패딩을 아주 약간 조정했습니다.

div.error {
    padding: 2px 5px;
}

You can change those numbers to increase/decrease the padding on top/bottom or left/right. You can also add a height and width to the error message. If you are still having issues, try to replace the span with a div

<div class="group">
<input type="radio" class="checkbox" value="P" id="radio_P" name="radio_group_name"/>
<label for="radio_P">P</label>
<input type="radio" class="checkbox" value="S" id="radio_S" name="radio_group_name"/>
<label for="radio_S">S</label>
</div>

And then give the container a width (this is very important)

div.group {
    width: 50px; /* or any other value */
}

About the blank page. As I said I tried your code and it is working for me. It might be something else in your code that is causing the issue.


I use jQuery BeautyTips to achieve the little bubble effect you are talking about. I don't use the Validation plugin so I can't really help much there, but it is very easy to style and show the BeautyTips. You should look into it. It's not as simple as just CSS rules, I'm afraid, as you need to use the canvas element and include an extra javascript file for IE to play nice with it.


A few things:

First, I don't think you really need a validation error for a radio fieldset because you could just have one of the fields checked by default. Most people would rather correct something then provide something. For instance:

   Age: (*) 12 - 18 | () 19 - 30 | 31 - 50 

is more likely to be changed to the right answer as the person DOESN'T want it to go to the default. If they see it blank, they are more likely to think "none of your business" and skip it.

Second, I was able to get the effect I think you are wanting without any positioning properties. You just add padding-right to the form (or the div of the form, whatever) to provide enough room for your error and make sure your error will fit in that area. Then, you have a pre-set up css class called "error" and you set it as having a negative margin-top roughly the height of your input field and a margin-left about the distance from the left to where your padding-right should start. I tried this out, it's not great, but it works with three properties and requires no floats or absolutes:

   <style type="text/css">
    .error {
        width: 13em; /* Ensures that the div won't exceed right padding of form */
        margin-top: -1.5em;  /*Moves the div up to the same level as input */
        margin-left: 11em;   /*Moves div to the right */
        font-size: .9em;     /*Makes sure that the error div is smaller than input */
    }

   <form>
   <label for="name">Name:</label><input id="name" type="textbox" />
   <div class="error"><<< This field is required!</div>
   <label for="numb">Phone:</label><input id="numb" type="textbox" />
   <div class="error"><<< This field is required!</div>
   </form>

Unfortunately I can't comment with my newbie reputation, but I have a solution for the issue of the screen going blank, or at least this is what worked for me. Instead of setting the wrapper class inside of the errorPlacement function, set it immediately when you're setting the wrapper type.

$('#myForm').validate({
    errorElement: "div",
    wrapper: "div class=\"message\"",
    errorPlacement: function(error, element) {
        offset = element.offset();
        error.insertBefore(element);
        //error.addClass('message');  // add a class to the wrapper
        error.css('position', 'absolute');
        error.css('left', offset.left + element.outerWidth() + 5);
        error.css('top', offset.top - 3);
    }

});

I'm assuming doing it this way allows the validator to know which div elements to remove, instead of all of them. Worked for me but I'm not entirely sure why, so if someone could elaborate that might help others out a ton.


That answer really helped me, in my case i had to filter some elements out and have special aligment on their error div,

errorPlacement:function(error,element) {
    if (element.attr("id") == "special_element") {
        // special align
    } else { // default error scheme
        error.insertAfter(element);
    }
}

Add following css to your .validate method to change the css or functionality

 errorElement: "div",
    wrapper: "div",
    errorPlacement: function(error, element) {
        offset = element.offset();
        error.insertAfter(element)
        error.css('color','red');
    }

If you could provide some reason as to why you need to replace the label with a div, that would certainly help...

또한 도움이되는 샘플 ( http://dpaste.com/ 또는 http://pastebin.com/ ) 을 붙여 주 시겠습니까?

참고 URL : https://stackoverflow.com/questions/860055/jquery-override-default-validation-error-message-display-css-popup-tooltip-lik

반응형