나는 이번에 '필수' 양식 요소 'dtep 클래스 잘못된 사실을 발견했다' 페이지 로드되는지 즉시 적용됩니다. 예를 들어, 이 경우 코드:
<style>
input:invalid { background-color: pink; color: white; }
input:valid { background-color: white; color: black; }
</style>
…
<input name="foo" required />
그런후에도 너회의 페이지는 로드형 비어 있는 핑크 입력입니다 요소점 때문이다. 하지만 난 HTML5 가 내장되어 있어 검증 멋지구리해요 don& # 39, 대부분의 사용자들이 작성되지는 양식을 they& 전에 검증하십시오 것 같지는 않다 # 39, 입력하십시오. 모든 값이 기회를 전혀 숨기지 않았다. 방법은 없나 지연입니다 적용을 dtep 클래스 보살피되 첫 번째 이벤트가 있는 영향을 미치는 요소 (양식 제출, 흐림의 변경하십시오 whatever&, # 39 에 해당)? Javascript 없이 이렇게 할 수 있습니까?
http://www.alistapart.com/articles/forward-thinking-form-validation/
>. 우리는 단지 그 후에는 이후 매핑하려는 나타내는 필드가 잘못되었습니다. >. 우리가 사용하는 데 초점을 둘, dtep 클래스 트리거할 잘못된 스타일. >. (당연히 필요한 모든 분야를 플래깅 처음부터 잘못된 >. 약간만이라도 가난한 설계 솔루션으로서의.)
이 같은 논리를 코드에 모습이 될 것 "이라고 말했다.
<style>
input:focus:required:invalid {background-color: pink; color: white;}
input:required:valid {background-color: white; color: black; }
<style>
여기서 만든 해야했다.
하지만 그럴 수 없는 순수 JavaScript 와 CSS 에서 수행할 수 있습니다. 이것은 [jQuery 예제] (
):<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 거짓값 바벨. 참 - >.
// use $.fn.one here to fire the event only once.
$(':required').one('blur keydown', function() {
console.log('touched', this);
$(this).addClass('touched');
});
/**
* All required inputs initially are yellow.
*/
:required {
background-color: lightyellow;
}
/**
* If a required input has been touched and is valid, it should be white.
*/
.touched:required:valid {
background-color: white;
}
/**
* If a required input has been touched and is invalid, it should be pink.
*/
.touched:required:invalid {
background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
<label>
Name:
<input type="text" required> *required
</label>
</p>
<p>
<label>Age:
<input type="text">
</label>
</p>
끝 - < 스니핏 >;!
이러한 문제의 답을 만료었습니다. 이제 와 CSS dtep 클래스 플레이스홀더를 확인하고 이를 확인할 수 있습니다.
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
input:not(:placeholder-shown):invalid {
background-color: salmon;
}
form:invalid button {
background-color: salmon;
pointer-events: none;
}
<form>
<input type="email" placeholder="[email protected]" required>
<button type="submit">Submit</button>
</form>
끝 - < 스니핏 >;!
처음에는 일반 배경 및 이메일 주소를 입력하면 등을 통해 핑크 너회가 불완전한 다르거든요.
이 저마다 mizilla 처리하는 모스 ᅴ 잘못된 # 39 they& 후 해당 qic 싸이도클레스 forms, ve been 상호 작용. 이 때문에 지원 부족 매든 사용을 권장하지 않습니다. 그러나 모질라 파이어폭스 수정할 수 있습니다.
그러나 이 경우, t help it 좋겠다 정말 doesn& # 39 는 일부 컨텍스트입니다.
[2]: https://drafts.csswg.org/selectors-4/ # 사용자 오류 dtep
내가 만든 작은 심 대응하기 위해 이 내 codebase. 그냥 내가 사용하는 ',' 요소 '노바리다트 form/> < 시작으로, 갖고 있는' 속성 ',' 함께 데이터 검증을 = " blur", 속성. 이 첫 번째 이벤트 안본다면 iqn 유형:. 이렇게 계속 사용할 수 있습니다 '토종' 잘못된 css 선택기를 폼 스타일.
$(function () {
$('[data-validate-on]').each(function () {
var $form = $(this);
var event_name = $form.data('validate-on');
$form.one(event_name, ':input', function (event) {
$form.removeAttr('novalidate');
});
});
});
이는 바닐라이스 (no jQuery) 버전의 크시 & # 39 의 답변
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 거짓값 바벨. 참 - >.
{
let f = function() {
this.classList.add('touched')
}
document
.querySelectorAll('input')
.forEach((e) => {
e.addEventListener('blur', f, false)
e.addEventListener('keydown', f, false)
})
}
/**
* All required inputs initially are yellow.
*/
:required {
background-color: lightyellow;
}
/**
* If a required input has been touched and is valid, it should be white.
*/
.touched:required:valid {
background-color: white;
}
/**
* If a required input has been touched and is invalid, it should be pink.
*/
.touched:required:invalid {
background-color: pink;
}
<p><label>
Name:
<input type="text" required> *required
</label></p>
<p><label>Age:
<input type="text">
</label></p>
끝 - < 스니핏 >;!
Html5 를 사용하는 동안 양식 검증, 잘못된 자료 제출 / 필드, 다시 발명 브라우저를 사용해 봅니다 탐지합니다 대신 잡았다.
& # 39 의 음악을 들을 수 있는 '잘못된' 이벤트 추가하기에서는 클래스용 invalid& # 39;; 데이터베이스에구성원을 양식. # 39, & # 39 를 invalid&. 또, CSS3 를 사용하여 클래스를 사용하여 마을 '스타일' 선택기를 dtep 양식에 이동할 수 있습니다.
예를 들면 다음과 같습니다.
// where myformid is the ID of your form
var myForm = document.forms.myformid;
var checkCustomValidity = function(field, msg) {
if('setCustomValidity' in field) {
field.setCustomValidity(msg);
} else {
field.validationMessage = msg;
}
};
var validateForm = function() {
// here, we're testing the field with an ID of 'name'
checkCustomValidity(myForm.name, '');
if(myForm.name.value.length < 4) {
checkCustomValidity(
// alerts fields error message response
myForm.name, 'Please enter a valid Full Name, here.'
);
}
};
/* here, we are handling your question above, by adding an invalid
class to the form if it returns invalid. Below, you'll notice
our attached listener for a form state of invalid */
var styleInvalidForm = function() {
myForm.className = myForm.className += ' invalid';
}
myForm.addEventListener('input', validateForm, false);
myForm.addEventListener('keyup', validateForm, false);
myForm.addEventListener('invalid', styleInvalidForm, true);
이제 단순히 & # 39, 스타일, 양식에 따라 적절하게 invalid& # 39. # 39, ve we& 클래스용 첨부됩니다.
예를 들면 다음과 같습니다.
form.invalid input:invalid,
form.invalid textarea:invalid {
background: rgba(255, 0, 0, .05);
border-color: #ff6d6d;
-webkit-box-shadow: 0 0 6px rgba(255, 0, 0, .35);
box-shadow: 0 0 6px rgba(255, 0, 0, .35);
}
있습니다 잘못된 '이벤트' 이벤트 'html5' (form 요소와 제출됩니다 전에 화재가 발생하지 않는 각 요소에 대한 전달하십시오 체크발리디티. 예를 들어, 이 이벤트 적용하십시오 클래스를 사용할 수 있는 주변 양식 및 디스플레이 잘못된 시켜버리므로 국한됨 이 사건 이후 발생합니다.
$("form input, form select, form textarea").on("invalid", function() {
$(this).closest('form').addClass('invalid');
});
Css 당신의 모습이 됩니다.
:invalid { box-shadow: none; }
.invalid input:invalid,
.invalid textarea:invalid,
.invalid select:invalid { border: 1px solid #A90909 !important; background-color: #EEC2C2; }
첫 번째 줄은 절감뿐만 기본값입니다 스타일을 양식 요소 때문에 여바바 중립 dell. 페이지 부하. 빨리 잘못된 이벤트 화재 (전송하려 할 때 양식), 요소가 눈에 띄게 렌더링됨 잘못되었습니다.
추상 클래스 ',' 좋은 방법은 잘못된 유효함 css 와 자바스크립트 입력 필드를 방관하겠나 초점을 맞춘 후 일부 여부를 확인할 수 있었다.
CSS.
input.dirty:invalid{ color: red; }
input.dirty:valid{ color: green; }
JS:
// Function to add class to target element
function makeDirty(e){
e.target.classList.toggle('dirty');
}
// get form inputs
var inputs = document.forms[0].elements;
// bind events to all inputs
for(let input of inputs){
input.addEventListener('invalid', makeDirty);
input.addEventListener('blur', makeDirty);
input.addEventListener('valid', makeDirty);
}
[데모] [1]
할 수 있도록 필요한 요소만 있는 이들에 대한 특정한 클래스 및 , 는 핑크. 각 필수 요소가 추가 이벤트 핸들러를 추가하는 갈 때 해당 클래스를 요소.
다음과 같은 항목을
<style>
input.touched:invalid { background-color: pink; color: white; }
input.touched:valid { background-color: white; color: black; }
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
var required = document.querySelectorAll('input:required');
for (var i = 0; i < required.length; ++i) {
(function(elem) {
function removeClass(name) {
if (elem.classList) elem.classList.remove(name);
else
elem.className = elem.className.replace(
RegExp('(^|\\s)\\s*' + name + '(?:\\s+|$)'),
function (match, leading) {return leading;}
);
}
function addClass(name) {
removeClass(name);
if (elem.classList) elem.classList.add(name);
else elem.className += ' ' + name;
}
// If you require a class, and you use JS to add it, you end up
// not showing pink at all if JS is disabled.
// One workaround is to have the class on all your elements anyway,
// and remove it when you set up proper validation.
// The main problem with that is that without JS, you see what you're
// already seeing, and stuff looks hideous.
// Unfortunately, you kinda have to pick one or the other.
// Let non-blank elements stay "touched", if they are already,
// so other stuff can make the element :invalid if need be
if (elem.value == '') addClass('touched');
elem.addEventListener('blur', function() {
addClass('touched');
});
// Oh, and when the form submits, they need to know about everything
if (elem.form) {
elem.form.addEventListener('submit', function() {
addClass('touched');
});
};
})(required[i]);
}
});
</script>
물론 이 같은 일을 won& # 39 는 IE8 이하, t, t (a) ',' 비교적 새롭고 wasn& # 39 는 IE8 표준 동콘텐트로데트 때 나온 것으로, (b) '' 보다는 'IE8 /dev/raw/raw1 스타슈벤트 dom 표준 addeventlistener', (c), 't care about' 필수 ie8 isn& # 39 갈 만큼 기술적으로 지원부에서는 t # 39, 어쨌든 doesn& html 5.
내 방식을 슬라이드에서는 피하기 위해 모든 초점을 흐림 입력입니다 기본값입니다 스타일을 잘못된 것으로, 그냥 단순한 추가해야 할 수 있도록 '집중' 및 '해당 웹페이지의 롱포쿠스' 명령 'js 식별하는 데 초점을 흐림' 투입물, 따라서 모든 입력 스타일을 나타나지 않습니다 잘못된 dell. 1 위를 차지했다.
<style>
input.focused:required:invalid { background-color: pink; color: white; }
input:valid { background-color: white; color: black; }
</style>
…
<input name="foo" class="notfocused" onFocus="document.activeElement.className='focused';" required />
Try it yourself (아래 참조).
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 거짓값 바벨. > 거짓값 -;
input.focused:required:invalid {
background-color: pink;
color: white;
}
input:required:valid {
background-color: darkseagreen;
color: black;
}
<label>At least 1 charater:</label><br />
<input type="text" name="foo" class="notfocused" onFocus="document.activeElement.className='focused';" required />
끝 - < 스니핏 >;!
내가 갈 수 있지만, s, t # 39 can& 주석문입니다 @Carl& # 39 함께 사용하여 매우 유용한 관한 답변을 없습니다. (자리표시자 표시됩니까). 다른 설명에 따르면 이 잘못된 상태가 계속 볼 수 있는 대로 없으면 자리표시자 (as 어떤 형태로든 디자인을 call for).
그래서 이 같은 문제를 해결하기 위해 빈 자리표시자 추가하면 됩니다
<input type="text" name="username" placeholder=" " required>
그런후에도 너회의 CSS 와 같은 일이
:not(:placeholder-shown):invalid{ background-color: #ff000038; }
협력했습니다 가져다줄래요!
다음과 같은) 에서 [아구세] (https://stackoverflow.com/users/1296306/aghouseh) & # 39 의 [생각] (https://stackoverflow.com/a/36070438/445547), 조금 떠날려하면 제출됩니다 버튼를 집중된 설정되었습니다 때 javascript 를 사용할 수 있고, 검증, 당시 무산되었다.
Javascript 가 추가하기에서는 클래스 (예: 버튼을 클릭할 때 집중된 또는 양식 필드를 제출됩니다 집중된 제출됩니다 '') 를 사용하면, 그 다음에 css 스타일 잘못된 투입물.
이 inet6.0 best practice 를 사용자가 입력한 후 검증을 마친 것으로 보여 주는 피드백 필드용 조사에 따르면, 이 과정에서 보여주는 추가 혜택을 받을 수 없다.
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. 참 - >.
document
.querySelector('input[type=submit]')
.onfocus = function() {
this
.closest('form')
.classList
.add('submit-focussed');
};
form.submit-focussed input:invalid {
border: thin solid red;
}
<form>
<label>Email <input type="email" required="" /></label>
<input type="submit" />
</form>
끝 - < 스니핏 >;!
"'javascript (함수 ($) { $ (& # 39, & # 39, 입력 [유형 = onsubmit]) 오언 (& # 39, focus& # 39, 함수 () { $ (이) 자파렌트 (& # 39, form& # 39;) 지아다클레스 (& # 39, submit-focussed& # 39;). }). }) (포함한다). / WordPress 호환적 / "'