사용자 정의 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일 현재 최신 버전 사용)
- 파이어폭스 40.0.3
- 오페라 31.0
구답
여기에서 이전 개정판을 볼 수 있습니다: https://stackoverflow.com/revisions/16069817/6
유효하지 않은 속성을 사용하여 이 작업을 수행할 수 있습니다. 이 데모 코드를 확인하십시오.
<form>
<input type="email" pattern="[^@]*@[^@]" required oninvalid="this.setCustomValidity('Put here custom message')"/>
<input type="submit"/>
</form>

코드펜 데모: https://codepen.io/akshaykhale1992/pen/yLNvOqP
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를 사용한 필드 검증 자바스크립트 코드입니다.
$(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가 메시지를 받기 때문에 각 필수 필드에 메시지를 설정할 수 있습니다.자바스크립트에서 각 필드를 바로 설정할 필요는 없고, jQuery가 대신 해줍니다.그 정규군은 괜찮은 것 같습니다. (적어도 당신의 것을 막습니다.)testing@.com! 하하)
fiddle에서 볼 수 있듯이, 제출 양식 이벤트에 대한 추가 검증을 수행합니다(이것은 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/ 그것이 도움이 되기를 바랍니다!
요소를 가져오고 메서드 setCustomValid를 사용하면 됩니다.
예
var foo = document.getElementById('foo');
foo.setCustomValidity(' An error occurred');
모든 입력 태그에 "title" 속성을 사용하고 메시지를 작성합니다.
단순히 oninvalid=" 특성을 사용하면 됩니다. 이는 bingding과 함께 사용할 수 있습니다.CustomValidity() eventListener를 설정합니다!
여기 제 데모 코드가 있습니다! (실행하여 확인하실 수 있습니다!) 
<!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/ #http=양식-설명
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와 같은 다른 유효 조건이 있습니다.
다음과 같이 유효하지 않은 특성에 사용합니다.
oninvalid="this.setCustomValidity('Special Characters are not allowed')
언급URL : https://stackoverflow.com/questions/13798313/set-custom-html5-required-field-validation-message
'programing' 카테고리의 다른 글
| Package Manager Console에서 이전 버전으로 "Update-Package"하려면 어떻게 해야 합니까? (0) | 2023.09.09 |
|---|---|
| MySQL 대 대 대 대 대 대 대 대 대 대 대다수 (0) | 2023.09.09 |
| Oracle에서 여러 문자열을 함께 바꾸는 방법 (0) | 2023.09.09 |
| Thymeleaf로 Spring Boot에서 플래시 메시지를 설정하는 방법 (0) | 2023.09.04 |
| MariaDB datetime 자동 업데이트 버그 (0) | 2023.09.04 |