HTML5와 일치하는 두 개의 양식 필드를 요구할 수 있습니까?
HTML5를 사용하여 일치하도록 두 양식 필드의 항목을 요구하는 방법이 있습니까? 아니면 여전히 자바 스크립트로해야합니까? 예를 들어, 두 개의 암호 필드가 있고 사용자가 각 필드에 동일한 데이터를 입력했는지 확인하려는 경우이를 달성하기 위해 수행 할 수있는 몇 가지 속성 또는 다른 코딩이 있습니까?
HTML5 유효성 검사와 정확히 일치하지는 않지만 약간의 JavaScript로 문제를 해결할 수 있습니다. 아래 예를 따르십시오.
<p>Password:</p>
<input name="password" required="required" type="password" id="password" />
<p>Confirm Password:</p>
<input name="password_confirm" required="required" type="password" id="password_confirm" oninput="check(this)" />
<script language='javascript' type='text/javascript'>
function check(input) {
if (input.value != document.getElementById('password').value) {
input.setCustomValidity('Password Must be Matching.');
} else {
// input is valid -- reset the error message
input.setCustomValidity('');
}
}
</script>
<br /><br />
<input type="submit" />
정규식 입력 패턴으로 할 수 있습니다 ( 브라우저 호환성 확인 )
<input id="password" name="password" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Must have at least 6 characters' : ''); if(this.checkValidity()) form.password_two.pattern = this.value;" placeholder="Password" required>
<input id="password_two" name="password_two" type="password" pattern="^\S{6,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '');" placeholder="Verify Password" required>
최소한의 자바 스크립트를 사용하는 간단한 솔루션은 html 속성 패턴 ( 대부분의 최신 브라우저에서 지원)을 사용하는 것입니다. 이것은 두 번째 필드의 패턴을 첫 번째 필드의 값으로 설정하여 작동합니다.
불행히도 표준 함수가없는 정규식도 이스케이프해야합니다.
<form>
<input type="text" oninput="form.confirm.pattern = escapeRegExp(this.value)">
<input name="confirm" pattern="" title="Fields must match" required>
</form>
<script>
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
</script>
JavaScript가 필요하지만 중간 <output>
요소와 oninput
양식 처리기를 사용하여 비교를 수행함으로써 코드의 양을 최소화 할 수 있습니다 (패턴 및 유효성 검사는이 솔루션을 보강 할 수 있지만 단순성을 위해 여기에 표시되지 않음).
<form oninput="result.value=!!p2.value&&(p1.value==p2.value)?'Match!':'Nope!'">
<input type="password" name="p1" value="" required />
<input type="password" name="p2" value="" required />
<output name="result"></output>
</form>
HTML5뿐만 아니라 약간의 JavaScript
클릭 [여기] https://codepen.io/diegoleme/pen/surIK
HTML
<form class="pure-form">
<fieldset>
<legend>Confirm password with HTML5</legend>
<input type="password" placeholder="Password" id="password" required>
<input type="password" placeholder="Confirm Password" id="confirm_password" required>
<button type="submit" class="pure-button pure-button-primary">Confirm</button>
</fieldset>
</form>
자바 스크립트
var password = document.getElementById("password")
, confirm_password = document.getElementById("confirm_password");
function validatePassword(){
if(password.value != confirm_password.value) {
confirm_password.setCustomValidity("Passwords Don't Match");
} else {
confirm_password.setCustomValidity('');
}
}
password.onchange = validatePassword;
confirm_password.onkeyup = validatePassword;
패턴과 정규식을 사용하는 답변은 사용자의 비밀번호를 입력 속성에 일반 텍스트로 씁니다 pattern='mypassword'
. 이것은 개발자 도구가 열려있는 경우에만 표시되지만 여전히 좋은 생각이 아닌 것 같습니다.
Another issue with using pattern to check for a match is that you are likely to want to use pattern to check that the password is of the right form, e.g. mixed letters and numbers.
I also think these methods won't work well if the user switches between inputs.
Here's my solution which uses a bit more JavaScript but performs a simple equality check when either input is updated and then sets a custom HTML validity. Both inputs can still be tested for a pattern such as email format or password complexity.
For a real page you would change the input types to 'password'.
<form>
<input type="text" id="password1" oninput="setPasswordConfirmValidity();">
<input type="text" id="password2" oninput="setPasswordConfirmValidity();">
</form>
<script>
function setPasswordConfirmValidity(str) {
const password1 = document.getElementById('password1');
const password2 = document.getElementById('password2');
if (password1.value === password2.value) {
password2.setCustomValidity('');
} else {
password2.setCustomValidity('Passwords must match');
}
console.log('password2 customError ', document.getElementById('password2').validity.customError);
console.log('password2 validationMessage ', document.getElementById('password2').validationMessage);
}
</script>
참고URL : https://stackoverflow.com/questions/9142527/can-you-require-two-form-fields-to-match-with-html5
'IT story' 카테고리의 다른 글
Apache Kafka 대 Apache Storm (0) | 2020.09.06 |
---|---|
GCC로 미리 컴파일 된 헤더 (0) | 2020.09.05 |
nodejs 로그 파일은 어디에 있습니까? (0) | 2020.09.05 |
RecyclerView에서 특정 항목을 업데이트 / 새로 고침하는 방법 (0) | 2020.09.05 |
PHP의 count () 함수는 배열에 대해 O (1) 또는 O (n)입니까? (0) | 2020.09.05 |