更改输入密码时的文本颜色

huangapple go评论56阅读模式
英文:

Change input colour while typing password

问题

我在处理一个注册表单,并且在最后一部分遇到了问题。我需要在所有正确的键都输入后,将输入边框从红色变为绿色。我希望这发生在键入时,而不是在提交后。所以一开始是红色的,但一旦输入了所有需要的键,它就会变成绿色。

const form = document.getElementById("signup-form");
const password = document.getElementById('password').value;
const passwordField = document.getElementById('password');
const confirmPassword = document.getElementById('confirm_password').value;
const confirmPasswordField = document.getElementById('confirm_password');

function formValidation() {
  // 密码字段
  passwordField.style.borderColor = "red";
  passwordField.classList.add("invalid");

  if (password === "") {
    passwordField.style.borderColor = "red";
    passwordField.classList.add("invalid");
    return false;
  } else {
    passwordField.style.borderColor = "green";
    passwordField.classList.remove("invalid");
    passwordField.classList.add("valid");
  }
}

function passwordFieldValidations() {
  var letter = document.getElementById("letter");
  var capital = document.getElementById("capital");
  var number = document.getElementById("number");
  var length = document.getElementById("length");

  // 当用户点击密码字段时,显示消息框
  passwordField.onclick = function () {
    document.getElementById("message").style.display = "block";
  }

  // 当用户点击密码字段外部时,隐藏消息框
  passwordField.onblur = function () {
    document.getElementById("message").style.display = "none";
  }

  passwordField.onkeyup = function () {
    // 验证小写字母
    var lowerCaseLetters = /[a-z]/g;
    if (passwordField.value.match(lowerCaseLetters)) {
      letter.classList.remove("invalid");
      letter.classList.add("valid");
    } else {
      letter.classList.remove("valid");
      letter.classList.add("invalid");
    }

    // 验证大写字母
    var upperCaseLetters = /[A-Z]/g;
    if (passwordField.value.match(upperCaseLetters)) {
      capital.classList.remove("invalid");
      capital.classList.add("valid");
    } else {
      capital.classList.remove("valid");
      capital.classList.add("invalid");
    }

    // 验证数字
    var numbers = /[0-9]/g;
    if (passwordField.value.match(numbers)) {
      number.classList.remove("invalid");
      number.classList.add("valid");
    } else {
      number.classList.remove("valid");
      number.classList.add("invalid");
    }

    // 验证长度
    if (passwordField.value.length >= 8) {
      length.classList.remove("invalid");
      length.classList.add("valid");
    } else {
      length.classList.remove("valid");
      length.classList.add("invalid");
    }

    if (letter.classList.contains("valid") &&
      capital.classList.contains("valid") &&
      number.classList.contains("valid") &&
      length.classList.contains("valid")) {
      passwordField.style.borderColor = "green";
      passwordField.classList.remove("invalid");
      passwordField.classList.add("valid");
    }
  }
}

form.addEventListener("submit", (e) => {
  var password1 = passwordField.value;
  var password2 = confirmPasswordField.value;
  if (password1 !== password2) {
    e.preventDefault()
    confirmPasswordField.style.borderColor = "red";
    confirmPasswordField.classList.add("invalid");
  } else {
    confirmPasswordField.style.borderColor = "green";
    confirmPasswordField.classList.remove("invalid");
    confirmPasswordField.classList.add("valid");
  }
});

document.getElementById("submit-form").addEventListener("click", formValidation);

以上是你提供的 JavaScript 代码的翻译。

英文:

I am working on a signup form and I am having trouble with this last section. I need the input border to turn from red to green once all the correct keys have been put in. I mean it to happen at the time of typing and not after submitting.
So it is red to begin but it turns green once you have pressed all the keys needed.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const form = document.getElementById(&quot;signup-form&quot;);
const password = document.getElementById(&#39;password&#39;).value;
const passwordField = document.getElementById(&#39;password&#39;);
const confirmPassword = document.getElementById(&#39;confirm_password&#39;).value;
const confirmPasswordField = document.getElementById(&#39;confirm_password&#39;);
function formValidation(){
// Password Field
passwordField.style.borderColor = &quot;red&quot;;
passwordField.classList.add(&quot;invalid&quot;);
if(password === &quot;&quot;){
passwordField.style.borderColor = &quot;red&quot;;
passwordField.classList.add(&quot;invalid&quot;);
return false;
}else{
passwordField.style.borderColor = &quot;green&quot;;
passwordField.classList.remove(&quot;invalid&quot;);
passwordField.classList.add(&quot;valid&quot;);
}
}    
function passwordFieldValidations() {
var letter = document.getElementById(&quot;letter&quot;);
var capital = document.getElementById(&quot;capital&quot;);
var number = document.getElementById(&quot;number&quot;);
var length = document.getElementById(&quot;length&quot;);
// When the user clicks on the password field, show the message box
passwordField.onclick = function() {
document.getElementById(&quot;message&quot;).style.display = &quot;block&quot;;
}
// When the user clicks outside of the password field, hide the message box
passwordField.onblur = function() {
document.getElementById(&quot;message&quot;).style.display = &quot;none&quot;;
}
passwordField.onkeyup = function() {
// Validate lowercase letters
var lowerCaseLetters = /[a-z]/g;
if(passwordField.value.match(lowerCaseLetters)) {  
letter.classList.remove(&quot;invalid&quot;);
letter.classList.add(&quot;valid&quot;);
} else {
letter.classList.remove(&quot;valid&quot;);
letter.classList.add(&quot;invalid&quot;);
}
// Validate capital letters
var upperCaseLetters = /[A-Z]/g;
if(passwordField.value.match(upperCaseLetters)) {  
capital.classList.remove(&quot;invalid&quot;);
capital.classList.add(&quot;valid&quot;);
} else {
capital.classList.remove(&quot;valid&quot;);
capital.classList.add(&quot;invalid&quot;);
}
// Validate numbers
var numbers = /[0-9]/g;
if(passwordField.value.match(numbers)) {  
number.classList.remove(&quot;invalid&quot;);
number.classList.add(&quot;valid&quot;);
} else {
number.classList.remove(&quot;valid&quot;);
number.classList.add(&quot;invalid&quot;);
}
// Validate length
if(passwordField.value.length &gt;= 8) {
length.classList.remove(&quot;invalid&quot;);
length.classList.add(&quot;valid&quot;);
} else {
length.classList.remove(&quot;valid&quot;);
length.classList.add(&quot;invalid&quot;);
}
if (letter.classList.contains(valid) &amp;&amp; capital.classList.contains(valid) 
&amp;&amp; number.classList.contains(valid) &amp;&amp; length.classList.contains(valid)) {
passwordField.style.borderColor = &quot;green&quot;;
passwordField.classList.remove(&quot;invalid&quot;);
passwordField.classList.add(&quot;valid&quot;);
}
}
}
form.addEventListener(&quot;submit&quot;, (e) =&gt; {
var password1 = passwordField.value;
var password2 = confirmPasswordField.value;
if(password1 !== password2) {
e.preventDefault()
confirmPasswordField.style.borderColor = &quot;red&quot;;
confirmPasswordField.classList.add(&quot;invalid&quot;);
} else { 
confirmPasswordField.style.borderColor = &quot;green&quot;;
confirmPasswordField.classList.remove(&quot;invalid&quot;);
confirmPasswordField.classList.add(&quot;valid&quot;);
}
});
document.getElementById(&quot;submit-form&quot;).addEventListener(&quot;click&quot;, formValidation);

<!-- language: lang-css -->

body { margin: 0; padding: 0; }
h1, h2 { font-family: &#39;Poppins&#39;, sans-serif; color: #fff; }
p, label, button { font-family: Roboto, sans-serif; }
#wrapper { width: 1200px; margin: 0 auto; }
#content { background-color: #272224; height: 600px; padding: 20px 0 0; }
#signup-info { margin: 0 auto; }
#signup-form { width: 400px; margin: 0 auto; }
#signup-info h2 img { width: 40px; vertical-align: middle; }
#signup-info h1 { margin-bottom: 0; }
.no-top-margin { margin-top: 0; }
#signup-info p { color: #FFE4CF; }
label { display: block; color: #fff; font-weight: bold; }
input { margin-bottom: 15px; border: none; border-bottom: 1px #555 solid; 
background-color: transparent; padding: 10px 0; width: 100%;
color: #FFE4CF; font-weight: bold;
}
::placeholder { font-weight: normal; }
button { border: none; background-color: #FFE4CF; width: 100%; padding: 15px; font-weight: bold; }
#signup-info a { color: #fff; }
input.valid { background-image: url(images/check.png); background-position: right; 
background-size: 10%; background-repeat: no-repeat; }
input.invalid { background-image: url(images/cross.png); background-position: right;
background-size: 10%; background-repeat: no-repeat; }
#message p { margin: 5px 0 5px 40px; }
#message h3 { margin: 0 0 5px 0; }
#message .valid { color: green; }
#message .valid:before { position: relative; left: -35px; content: &quot;✔&quot;; }
/* Add a red text color and an &quot;x&quot; when the requirements are wrong */
#message .invalid { color: red; }
#message .invalid:before { position: relative; left: -35px; content: &quot;✖&quot;; }
#message { display: none; background-color: #fff; padding: 10px; }
input.valid:focus { outline: none !important; border:1px solid green; }
::-ms-reveal { filter: invert(100%); }

<!-- language: lang-html -->

&lt;div id=&quot;wrapper&quot;&gt;
&lt;div id=&quot;content&quot;&gt;
&lt;div id=&quot;signup-info&quot;&gt;
&lt;form name=&quot;signup-form&quot; id=&quot;signup-form&quot; action=&quot;#&quot; method=&quot;post&quot;&gt;
&lt;div&gt;
&lt;label for=&quot;password&quot;&gt;Password:&lt;/label&gt;
&lt;input type=&quot;password&quot; name=&quot;password&quot; id=&quot;password&quot; placeholder=&quot;Enter a password&quot; 
pattern=&quot;(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}&quot; 
title=&quot;Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters&quot; required onfocus=&quot;passwordFieldValidations()&quot;&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;label for=&quot;confirm_password&quot;&gt;Confirm Password:&lt;/label&gt;
&lt;input type=&quot;password&quot; name=&quot;confirm_password&quot; id=&quot;confirm_password&quot; placeholder=&quot;Retype password&quot; 
title=&quot;Password must match&quot; required onkeyup=&quot;matchPasswords()&quot;&gt;
&lt;/div&gt;
&lt;button type=&quot;submit&quot; id=&quot;submit-form&quot;&gt;Create account&lt;/button&gt;
&lt;div id=&quot;message&quot;&gt;
&lt;h3&gt;Password must contain the following:&lt;/h3&gt;
&lt;p id=&quot;letter&quot; class=&quot;invalid&quot;&gt;A &lt;b&gt;lowercase&lt;/b&gt; letter&lt;/p&gt;
&lt;p id=&quot;capital&quot; class=&quot;invalid&quot;&gt;A &lt;b&gt;capital (uppercase)&lt;/b&gt; letter&lt;/p&gt;
&lt;p id=&quot;number&quot; class=&quot;invalid&quot;&gt;A &lt;b&gt;number&lt;/b&gt;&lt;/p&gt;
&lt;p id=&quot;length&quot; class=&quot;invalid&quot;&gt;Minimum &lt;b&gt;8 characters&lt;/b&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

答案1

得分: 1

你已经相当接近了。 更改输入密码时的文本颜色

在密码验证部分末尾附近,您意外地将valid用作标识符而不是字符串,应将classList.contains(valid)更改为classList.contains("valid")

// 所有这些调用中的 contains(valid) 应更改为 contains("valid"):
if (letter.classList.contains("valid") && capital.classList.contains("valid") 
        && number.classList.contains("valid") && length.classList.contains("valid")) {
      passwordField.style.borderColor = "green";
      passwordField.classList.remove("invalid");
      passwordField.classList.add("valid");
} else {
  // 还需要在此处添加一个else,将borderColor更改为"red",添加"invalid",移除"valid",然后完成!
}

提示: 在使用JavaScript时,始终保持浏览器控制台处于打开状态,以便及早检测任何错误和警告并加以修复。

另一个可以使用的技巧(有助于编写更清晰和易维护的代码)是在onkeyup事件处理程序的开头定义一个变量hasErrors,将其赋值为false,然后一旦以下检查之一失败,将其值设置为true

这是这个想法的基本逻辑:

var hasErrors = false;

// 验证数字
var numbers = /[0-9]/g;
if(passwordField.value.match(numbers)) {  
  ...
} else {
  hasErrors = true;
  ...
}

// 验证长度
if(passwordField.value.length >= 8) {
  ...
} else {
  hasErrors = true;
  ...
}

if (hasErrors) {
  // 处理错误情况(例如,红色边框)
} else {
  // 处理成功情况(例如,绿色边框)
}

此外,正如Scott Marcus提到的,最好使用addEventListener("keyup")形式而不是onkeyup。这里有一个详细的Stack Overflow答案解释了使用前者的好处。

英文:

You are actually pretty close. 更改输入密码时的文本颜色

You accidentally used valid as an identifier instead of a string in the classList.contains(valid) expression near the end of the password verification section:

// contains(valid) should be contains(&quot;valid&quot;) in all this calls:
if (letter.classList.contains(valid) &amp;&amp; capital.classList.contains(valid) 
        &amp;&amp; number.classList.contains(valid) &amp;&amp; length.classList.contains(valid)) {
      passwordField.style.borderColor = &quot;green&quot;;
      passwordField.classList.remove(&quot;invalid&quot;);
      passwordField.classList.add(&quot;valid&quot;);
} else {
  // You also need to add an else here, change the borderColor to &quot;red&quot;, add &quot;invalid&quot;, remove &quot;valid&quot;, and you&#39;re done!
}

Tip: Always have the browser console open when working with JavaScript in order to detect any errors and warnings early on an fix them.

Another trick that you can use (which leads to cleaner and more maintainable code) is to define a variable hasErrors at the beginning of the onkeyup event handler, assign the value false, and then set the value to true once any of the following checks fails.

Here's the basic logic behind this:

    var hasErrors = false;

    // Validate numbers
    var numbers = /[0-9]/g;
    if(passwordField.value.match(numbers)) {  
      ...
    } else {
      hasErrors = true;
      ...
    }

    // Validate length
    if(passwordField.value.length &gt;= 8) {
      ...
    } else {
      hasErrors = true;
      ...
    }

    if ( hasErrors ) {
      // Handle error case (e.g. red border)
    } else {
      // Handle success (e.g. green border) 
    }

Also, as Scott Marcus mentioned, it's better to use the addEventListener(&quot;keyup&quot;) form instead of the onkeyup. Here's a nice extensive SO answer that explains the benefits of using the former.

答案2

得分: -1

你可以尝试将变量"password"转换为"let",然后在函数"formValidation()"中使用"document.getElementById('password').value"设置变量"password"。

// 在函数formValidation()中设置变量password的值
function formValidation() {
    // 设置password变量的值
    password = document.getElementById('password').value;

    // 其他代码...
}

这是你要翻译的代码部分。

英文:

You can try with transform variable password to let and then in the function formValidation() set variable password with document.getElementById('password').value;

<!-- begin snippet: js hide: false console: true babel: null -->

<!-- language: lang-js -->

const form = document.getElementById(&quot;signup-form&quot;);
let password = document.getElementById(&#39;password&#39;).value;
const passwordField = document.getElementById(&#39;password&#39;);
const confirmPassword = document.getElementById(&#39;confirm_password&#39;).value;
const confirmPasswordField = document.getElementById(&#39;confirm_password&#39;);
function formValidation(){
// Password Field

//set password value again

  password = document.getElementById(&#39;password&#39;).value;
passwordField.style.borderColor = &quot;red&quot;;
passwordField.classList.add(&quot;invalid&quot;);
if(password === &quot;&quot;){
passwordField.style.borderColor = &quot;red&quot;;
passwordField.classList.add(&quot;invalid&quot;);
return false;
}else{
passwordField.style.borderColor = &quot;green&quot;;
passwordField.classList.remove(&quot;invalid&quot;);
passwordField.classList.add(&quot;valid&quot;);
}
}    
function passwordFieldValidations() {
var letter = document.getElementById(&quot;letter&quot;);
var capital = document.getElementById(&quot;capital&quot;);
var number = document.getElementById(&quot;number&quot;);
var length = document.getElementById(&quot;length&quot;);
// When the user clicks on the password field, show the message box
passwordField.onclick = function() {
document.getElementById(&quot;message&quot;).style.display = &quot;block&quot;;
}
// When the user clicks outside of the password field, hide the message box
passwordField.onblur = function() {
document.getElementById(&quot;message&quot;).style.display = &quot;none&quot;;
}
passwordField.onkeyup = function() {
// Validate lowercase letters
var lowerCaseLetters = /[a-z]/g;
if(passwordField.value.match(lowerCaseLetters)) {  
letter.classList.remove(&quot;invalid&quot;);
letter.classList.add(&quot;valid&quot;);
} else {
letter.classList.remove(&quot;valid&quot;);
letter.classList.add(&quot;invalid&quot;);
}
// Validate capital letters
var upperCaseLetters = /[A-Z]/g;
if(passwordField.value.match(upperCaseLetters)) {  
capital.classList.remove(&quot;invalid&quot;);
capital.classList.add(&quot;valid&quot;);
} else {
capital.classList.remove(&quot;valid&quot;);
capital.classList.add(&quot;invalid&quot;);
}
// Validate numbers
var numbers = /[0-9]/g;
if(passwordField.value.match(numbers)) {  
number.classList.remove(&quot;invalid&quot;);
number.classList.add(&quot;valid&quot;);
} else {
number.classList.remove(&quot;valid&quot;);
number.classList.add(&quot;invalid&quot;);
}
// Validate length
if(passwordField.value.length &gt;= 8) {
length.classList.remove(&quot;invalid&quot;);
length.classList.add(&quot;valid&quot;);
} else {
length.classList.remove(&quot;valid&quot;);
length.classList.add(&quot;invalid&quot;);
}
if  (letter.classList.contains(valid) &amp;&amp; capital.classList.contains(valid) 
&amp;&amp; number.classList.contains(valid) &amp;&amp; length.classList.contains(valid)) {
passwordField.style.borderColor = &quot;green&quot;;
passwordField.classList.remove(&quot;invalid&quot;);
passwordField.classList.add(&quot;valid&quot;);
}
}
}
form.addEventListener(&quot;submit&quot;, (e) =&gt; {
var password1 = passwordField.value;
var password2 = confirmPasswordField.value;
if(password1 !== password2) {
e.preventDefault()
confirmPasswordField.style.borderColor = &quot;red&quot;;
confirmPasswordField.classList.add(&quot;invalid&quot;);
} else { 
confirmPasswordField.style.borderColor = &quot;green&quot;;
confirmPasswordField.classList.remove(&quot;invalid&quot;);
confirmPasswordField.classList.add(&quot;valid&quot;);
}
});
document.getElementById(&quot;submit-form&quot;).addEventListener(&quot;click&quot;, formValidation);

<!-- language: lang-css -->

body {
margin: 0;
padding: 0;
}
h1,
h2 {
font-family: &#39;Poppins&#39;, sans-serif;
color: #fff;
}
p,
label,
button {
font-family: Roboto, sans-serif;
}
#wrapper {
width: 1200px;
margin: 0 auto;
}
#content {
background-color: #272224;
height: 600px;
padding: 20px 0 0;
}
#signup-info {
margin: 0 auto;
}
#signup-form {
width: 400px;
margin: 0 auto;
}
#signup-info h2 img {
width: 40px;
vertical-align: middle;
}
#signup-info h1 {
margin-bottom: 0;
}
.no-top-margin {
margin-top: 0;
}
#signup-info p {
color: #FFE4CF;
}
label {
display: block;
color: #fff;
font-weight: bold;
}
input {
margin-bottom: 15px;
border: none;
border-bottom: 1px #555 solid;
background-color: transparent;
padding: 10px 0;
width: 100%;
color: #FFE4CF;
font-weight: bold;
}
::placeholder {
font-weight: normal;
}
button {
border: none;
background-color: #FFE4CF;
width: 100%;
padding: 15px;
font-weight: bold;
}
#signup-info a {
color: #fff;
}
input.valid {
background-image: url(images/check.png);
background-position: right;
background-size: 10%;
background-repeat: no-repeat;
}
input.invalid {
background-image: url(images/cross.png);
background-position: right;
background-size: 10%;
background-repeat: no-repeat;
}
#message p {
margin: 5px 0 5px 40px;
}
#message h3 {
margin: 0 0 5px 0;
}
#message .valid {
color: green;
}
#message .valid:before {
position: relative;
left: -35px;
content: &quot;✔&quot;;
}
/* Add a red text color and an &quot;x&quot; when the requirements are wrong */
#message .invalid {
color: red;
}
#message .invalid:before {
position: relative;
left: -35px;
content: &quot;✖&quot;;
}
#message {
display: none;
background-color: #fff;
padding: 10px;
}
input.valid:focus {
outline: none !important;
border:1px solid green;
}
::-ms-reveal {
filter: invert(100%);
}

<!-- language: lang-html -->

&lt;body&gt;
&lt;div id=&quot;wrapper&quot;&gt;
&lt;div id=&quot;content&quot;&gt;
&lt;div id=&quot;signup-info&quot;&gt;
&lt;form name=&quot;signup-form&quot; id=&quot;signup-form&quot; action=&quot;#&quot; method=&quot;post&quot;&gt;
&lt;div&gt;
&lt;label for=&quot;password&quot;&gt;Password:&lt;/label&gt;
&lt;input type=&quot;password&quot; name=&quot;password&quot; id=&quot;password&quot; placeholder=&quot;Enter a password&quot; pattern=&quot;(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}&quot; 
title=&quot;Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters&quot; required onfocus=&quot;passwordFieldValidations()&quot;&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;label for=&quot;confirm_password&quot;&gt;Confirm Password:&lt;/label&gt;
&lt;input type=&quot;password&quot; name=&quot;confirm_password&quot; id=&quot;confirm_password&quot; placeholder=&quot;Retype password&quot; 
title=&quot;Password must match&quot; required onkeyup=&quot;matchPasswords()&quot;&gt;
&lt;/div&gt;
&lt;button type=&quot;submit&quot; id=&quot;submit-form&quot;&gt;Create account&lt;/button&gt;
&lt;div id=&quot;message&quot;&gt;
&lt;h3&gt;Password must contain the following:&lt;/h3&gt;
&lt;p id=&quot;letter&quot; class=&quot;invalid&quot;&gt;A &lt;b&gt;lowercase&lt;/b&gt; letter&lt;/p&gt;
&lt;p id=&quot;capital&quot; class=&quot;invalid&quot;&gt;A &lt;b&gt;capital (uppercase)&lt;/b&gt; letter&lt;/p&gt;
&lt;p id=&quot;number&quot; class=&quot;invalid&quot;&gt;A &lt;b&gt;number&lt;/b&gt;&lt;/p&gt;
&lt;p id=&quot;length&quot; class=&quot;invalid&quot;&gt;Minimum &lt;b&gt;8 characters&lt;/b&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年7月14日 05:12:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76683269.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定