IT

맞춤 HTML5 필수 항목 확인 메시지 설정

lottoking 2020. 8. 3. 17:26
반응형

맞춤 HTML5 필수 항목 확인 메시지 설정


필수 필드 사용자 정의 유효성 검사

입력 필드가 많은 양식이 하나 있습니다. html5 유효성 검사를 넣었습니다.

<input type="text" name="topicName" id="topicName" required />

이 텍스트 상자를 채우지 않고 양식을 신청하면 다음과 같은 기본 메시지가 표시됩니다.

"Please fill out this field"

누구 든지이 메시지를 편집하도록 도와 줄 수 있습니까?

편집 할 자바 펼쳐 코드가 작동하지 않습니다.

$(document).ready(function() {
    var elements = document.getElementsByName("topicName");
    for (var i = 0; i < elements.length; i++) {
        elements[i].oninvalid = function(e) {
            e.target.setCustomValidity("");
            if (!e.target.validity.valid) {
                e.target.setCustomValidity("Please enter Room Topic Title");
            }
        };
        elements[i].oninput = function(e) {
            e.target.setCustomValidity("");
        };
    }
})


이메일 사용자 정의

HTML 양식을 작성하고 있습니다.

<form id="myform">
    <input id="email" name="email" type="email" />
    <input type="submit" />
</form>


내가 원하는 확인 메시지.

필수 필드 : 이메일 주소를 입력하십시오.
잘못된 이메일 : 'testing @ .com'은 유효한 이메일 주소가 아닙니다. ( 여기에 텍스트 상자에 이메일 주소 입력 )

나는 시도 시도했다.

function check(input) {  
    if(input.validity.typeMismatch){  
        input.setCustomValidity("'" + input.value + "' is not a Valid Email Address.");  
    }  
    else {  
        input.setCustomValidity("");  
    }                 
}  

이 기능이 작동하지 않습니다. 다른 방법이 있습니까? 감사하겠습니다.


코드 스 니펫

이 답변은 매우 주목할만한 여기에 내가 구성 할 수있는 멋진 구성이 있습니다.

/**
  * @author ComFreek <https://stackoverflow.com/users/603003/comfreek>
  * @link https://stackoverflow.com/a/16069817/603003
  * @license MIT 2013-2015 ComFreek
  * @license[dual licensed] CC BY-SA 3.0 2013-2015 ComFreek
  * You MUST retain this license header!
  */
(function (exports) {
    function valOrFunction(val, ctx, args) {
        if (typeof val == "function") {
            return val.apply(ctx, args);
        } else {
            return val;
        }
    }

    function InvalidInputHelper(input, options) {
        input.setCustomValidity(valOrFunction(options.defaultText, window, [input]));

        function changeOrInput() {
            if (input.value == "") {
                input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
            } else {
                input.setCustomValidity("");
            }
        }

        function invalid() {
            if (input.value == "") {
                input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
            } else {
               input.setCustomValidity(valOrFunction(options.invalidText, window, [input]));
            }
        }

        input.addEventListener("change", changeOrInput);
        input.addEventListener("input", changeOrInput);
        input.addEventListener("invalid", invalid);
    }
    exports.InvalidInputHelper = InvalidInputHelper;
})(window);

용법

jsFiddle

<input id="email" type="email" required="required" />
InvalidInputHelper(document.getElementById("email"), {
  defaultText: "Please enter an email address!",

  emptyText: "Please enter an email address!",

  invalidText: function (input) {
    return 'The email address "' + input.value + '" is invalid!';
  }
});

자세한 내용은

  • defaultText 처음에 표시됩니다
  • emptyText 입력이 비어있을 때 표시됩니다.
  • invalidText 브라우저에서 입력이 유효하지 않은 경우 표시 될 경우 (예 : 유효한 이메일 주소가 아닌 경우)

세 가지 속성에 추가나 함수를 할당 할 수 있습니다.
함수를 지정하면 입력 요소 (DOM 노드)에 대한 참조를 승인 할 수 있고 표시를 리턴해야합니다 .

계속

테스트 대상 :

  • 크롬 카나리아 47.0.2
  • IE 11
  • Microsoft Edge (2015 년 8 월 28 일 현재 최신 버전 사용)
  • Firefox 40.0.3
  • 오페라 31.0

이전 답변

https://stackoverflow.com/revisions/16069817/6 에서 이전 개정을 볼 수 있습니다.


oninvalid 속성을 사용하여 간단히 달성 할 수 있습니다.

<form>
<input type="email" pattern="[^@]*@[^@]" required oninvalid="this.setCustomValidity('Put  here custom message')"/>
<input type="submit"/>
</form>

여기에 이미지 설명을 입력하십시오


HTML :

<form id="myform">
    <input id="email" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);"  type="email" required="required" />
    <input type="submit" />
</form>

자바 펼쳐 :

function InvalidMsg(textbox) {
    if (textbox.value == '') {
        textbox.setCustomValidity('Required email address');
    }
    else if (textbox.validity.typeMismatch){{
        textbox.setCustomValidity('please enter a valid email address');
    }
    else {
       textbox.setCustomValidity('');
    }
    return true;
}

스템 :

http://jsfiddle.net/patelriki13/Sqq8e/


이 시도 :

$(function() {
    var elements = document.getElementsByName("topicName");
    for (var i = 0; i < elements.length; i++) {
        elements[i].oninvalid = function(e) {
            e.target.setCustomValidity("Please enter Room Topic Title");
        };
    }
})

나는 Chrome과 FF에서 테스트를 두 브라우저에서 모두 작동했습니다.


사람, 나는 HTML 5에서 그런 짓을 한 적이 없지만 시도 할 것입니다. 바이올린을이 살펴보십시오 .

입력 태그에 jQuery, HTML5 기본 이벤트 및 속성 및 사용자 정의 속성을 사용했습니다. 모든 브라우저에서 테스트 전면 작동 할 수 있습니다.

다음은 jQuery를 사용 필드 유효성 검사 JavaScript 코드입니다.

$(document).ready(function()
{
    $('input[required], input[required="required"]').each(function(i, e)
    {
        e.oninput = function(el)
        {
            el.target.setCustomValidity("");

            if (el.target.type == "email")
            {
                if (el.target.validity.patternMismatch)
                {
                    el.target.setCustomValidity("E-mail format invalid.");

                    if (el.target.validity.typeMismatch)
                    {
                         el.target.setCustomValidity("An e-mail address must be given.");
                    }
                }
            }
        };

        e.oninvalid = function(el)
        {
            el.target.setCustomValidity(!el.target.validity.valid ? e.attributes.requiredmessage.value : "");
        };
    });
});

좋아요. 다음은 간단한 양식 html입니다.

<form method="post" action="" id="validation">
    <input type="text" id="name" name="name" required="required" requiredmessage="Name is required." />
    <input type="email" id="email" name="email" required="required" requiredmessage="A valid E-mail address is required." pattern="^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9]+$" />

    <input type="submit" value="Send it!" />
</form>

속성 requiredmessage은 내가 말한 사용자 지정 속성입니다. 각 필수 필드에 대한 메시지를 설정할 수 있으며, 오류 메시지를 표시 할 때 jQuery가 가져 오게됩니다. JavaScript에서 각 필드를 바로 설정할 필요가 없습니다. jQuery가 자동으로 수행합니다. 그 정규식은 괜찮은 것 같습니다 (적어도 그것은 당신을 차단합니다 testing@.com! 하하)

바이올린에서 볼 수 있듯이 제출 양식 이벤트에 대한 추가 유효성 검사를 수행합니다 ( 이는 document.ready에도 적용됩니다 ).

$("#validation").on("submit", function(e)
{
    for (var i = 0; i < e.target.length; i++)
    {
        if (!e.target[i].validity.valid)
        {
            window.alert(e.target.attributes.requiredmessage.value);
            e.target.focus();
            return false;
        }
    }
});

어쨌든 이것이 효과가 있거나 도움이되기를 바랍니다.


이것은 나를 위해 잘 작동합니다.

jQuery(document).ready(function($) {
    var intputElements = document.getElementsByTagName("INPUT");
    for (var i = 0; i < intputElements.length; i++) {
        intputElements[i].oninvalid = function (e) {
            e.target.setCustomValidity("");
            if (!e.target.validity.valid) {
                if (e.target.name == "email") {
                    e.target.setCustomValidity("Please enter a valid email address.");
                } else {
                    e.target.setCustomValidity("Please enter a password.");
                }
            }
        }
    }
});

및 (잘린) 함께 사용중인 양식 :

<form id="welcome-popup-form" action="authentication" method="POST">
    <input type="hidden" name="signup" value="1">
    <input type="email" name="email" id="welcome-email" placeholder="Email" required></div>
    <input type="password" name="passwd" id="welcome-passwd" placeholder="Password" required>
    <input type="submit" id="submitSignup" name="signup" value="SUBMIT" />
</form>

여기에 이미지 설명을 입력하십시오


동일한 유형의 모든 입력에 대해 '유효하지 않은'이벤트 리스너를 설정하거나 필요한 항목에 따라 하나만 설정 한 다음 적절한 메시지를 설정할 수 있습니다.

[].forEach.call( document.querySelectorAll('[type="email"]'), function(emailElement) {
    emailElement.addEventListener('invalid', function() {
        var message = this.value + 'is not a valid email address';
        emailElement.setCustomValidity(message)
    }, false);

    emailElement.addEventListener('input', function() {
        try{emailElement.setCustomValidity('')}catch(e){}
    }, false);
    });

스크립트의 두 번째 부분은 유효성 메시지가 재설정됩니다. 그렇지 않으면 양식을 제출할 수 없기 때문입니다. 예를 들어 이메일 주소가 수정 된 경우에도 메시지가 트리거되지 않습니다.

또한 입력을 입력하기 시작하면 '유효하지 않음'이 트리거되므로 필요에 따라 입력 필드를 설정할 필요가 없습니다.

이에 대한 바이올린이 있습니다 : http://jsfiddle.net/napy84/U4pB7/2/ 도움이 되었기를 바랍니다!


요소를 가져 와서 setCustomValidity 메소드를 사용하기 만하면됩니다.

var foo = document.getElementById('foo');
foo.setCustomValidity(' An error occurred');

모든 입력 태그에 "title"속성을 사용하고 그 위에 메시지를 작성합니다.


this.setCustomValidity () eventListener 를 연결하여 oninvalid = " 속성 만 사용하면 됩니다 !

여기 내 데모 코드가 있습니다! (체크 아웃하여 언어 수 있습니다!) 여기에 이미지 설명을 입력하십시오

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>oninvalid</title>
</head>
<body>
    <form action="https://www.google.com.hk/webhp?#safe=strict&q=" method="post" >
        <input type="email" placeholder="xgqfrms@email.xyz" required="" autocomplete="" autofocus="" oninvalid="this.setCustomValidity(`This is a customlised invalid warning info!`)">
        <input type="submit" value="Submit">
    </form>
</body>
</html>

참조 링크

http://caniuse.com/#feat=form-validation

https://www.w3.org/TR/html51/sec-forms.html#sec-constraint-validation


자신의 메시지를 표시하기 위해이 펼쳐서 추가 할 수 있습니다.

 <script>
     input = document.getElementById("topicName");

            input.addEventListener('invalid', function (e) {
                if(input.validity.valueMissing)
                {
                    e.target.setCustomValidity("Please enter topic name");
                }
//To Remove the sticky error message at end write


            input.addEventListener('input', function (e) {
                e.target.setCustomValidity('');
            });
        });

</script>

패턴 불일치와 같은 다른 유효성 검사의 경우 추가 조건을 추가 할 수 있습니다.

처럼

else if (input.validity.patternMismatch) 
{
  e.target.setCustomValidity("Your Message");
}

rangeOverflow, rangeUnderflow, stepMismatch, typeMismatch, valid와 같은 다른 유효성 조건이 있습니다.

참고 URL : https://stackoverflow.com/questions/13798313/set-custom-html5-required-field-validation-message

반응형