我为密码写了一些验证码,并确认密码是否匹配。此外,还有一个条件是检查我的密码长度是否小于6个字符,如果小于6个字符,则写入/显示错误。但是我的代码没有正常工作:当我切换到字段2时,字段1的条件没有被检查,如果两个条件都正确,则错误仍然存在。
这是我的代码:
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value == pass2.value){
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
if(pass1.length > 5){
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
}
else{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
}

<input name="password" type="password" placeholder="password" id="pass1"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
&#13;
答案 0 :(得分:12)
试试这个:
if(pass1.value.length > 5)
答案 1 :(得分:11)
使用以下代码。 首先,pass1.length
不正确。你应该写pass1.value.length
。 其次,我添加了比较最后的2个块,因为首先应该检查第一个块的长度。此外,还应该在第一个块的更改时调用该函数。
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value.length > 5)
{
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
}
else
{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
return;
}
if(pass1.value == pass2.value)
{
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else
{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
}
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="checkPass(); return false;" />
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
答案 2 :(得分:8)
之前:
if(pass1.length > 5)
后:
if(pass1.value.length > 5)
你应该在一切都适合之后检查相等,比如长度或允许的字符等。
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value.length > 5 && pass2.value.length > 5)
{
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
if(pass1.value == pass2.value)
{
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else
{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
}
else
{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
}
<input name="password" type="password" placeholder="password" id="pass1"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
答案 3 :(得分:7)
if (pass1.value.length > 5)
请确保不要应用trim()因为trim会删除空格并且密码中的空格不是有效字符。
答案 4 :(得分:6)
当您检查pass1的长度时,您实际上并没有检查它的值 - pass1.length > 5
- 您应该将其更改为pass1.value.length > 5
答案 5 :(得分:6)
你可以这样做:
if (pass1.value.trim().length > 5)
答案 6 :(得分:6)
要检查长度,你应该像这样写
if (pass1.value.length > 5)
然后你的代码正常工作
答案 7 :(得分:5)
您可以利用正则表达式为您进行验证。 例如:我允许在此密码中使用一些特殊字符,并且计数大于6
regex = pass1.value.search(/^[a-zA-Z0-9+&@#/%?=~_|!:,.;]{6,}+$/);
if(regex){
message.innerHTML="Invalid Password.";
}else{
message.innerHTML = " you have to enter at least 6 digit!";
}
答案 8 :(得分:4)
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value == pass2.value){
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
if(pass1.value.length > 5){
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
}
else{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
}
&#13;
<input name="password" type="password" placeholder="password" id="pass1"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
&#13;
答案 9 :(得分:4)
密码验证这一看似简单的任务可能会变得复杂,并且可能很难确定代码无法按预期工作的原因。挑战的主要部分在于指定条件逻辑,然后将此逻辑转换为工作代码。
您希望实现以下目标:
将此转换为条件逻辑(伪代码)的一种方法如下:
if (password length is less than 6)
inform user that password should be at least 6 characters
else if (passwords do not match)
ask user to confirm password
else
inform user that passwords match, all is ok
但我的代码无法正常工作:当我切换到字段2时,不检查字段1的条件,如果两个条件都正确,则错误仍然存在。
您的代码遵循不同的逻辑(伪代码):
if (passwords match)
inform user that passwords match, all is ok
else
inform user that passwords do not match
if (password is more than 5 characters)
inform user that the password is long enough
else
inform user that the password should be at least 6 characters
你的代码中的一个问题是密码长度是你检查的最后一件事,所以第一个if / else检查是多余的(即使密码匹配也不会产生任何相关的反馈),因为你的代码总是会结束提供有关密码长度的反馈。
另一个问题是你的代码会接受匹配的密码,即使它们少于6个字符,这就是你要先检查密码长度,然后检查两个密码是否匹配的原因。
此外,您的代码仅在用户写入字段2('#pass2')时运行这些检查,您还需要向字段1的'onkeyup'添加事件处理程序。
因此,您的代码逻辑需要重写。以下是可以采取的几种方法之一:
function checkPass() {
var neutralColor = '#fff'; // 'white';
var badColor = '#f66'; // 'red';
var goodColor = '#6f6'; // 'green';
var password1 = getElm('pass1').value;
var password2 = getElm('pass2').value;
//if password length is less than 6
if (password1.length < 6) {
feedback('Enter a password of at least 6 characters');
//we do not care about pass2 when pass1 is too short
setBGColor('pass2', neutralColor);
//if pass1 is blank, set neutral background
if (password1.length === 0) {
setBGColor('pass1', neutralColor);
} else {
setBGColor('pass1', badColor);
}
//else if passwords do not match
} else if (password2 !== password1) {
//we now know that pass1 is long enough
feedback('Confirm password');
setBGColor('pass1', goodColor);
//if pass2 is blank, set neutral background
if (password2.length === 0) {
setBGColor('pass2', neutralColor);
} else {
setBGColor('pass2', badColor);
}
//else all is well
} else {
feedback('Passwords match');
setBGColor('pass1', goodColor);
setBGColor('pass2', goodColor);
}
}
//helper function for document.getElementById()
function getElm(id) {
return document.getElementById(id);
}
//helper function for setting background color
function setBGColor(id, value) {
getElm(id).style.backgroundColor = value;
}
//helper function for feedback message
function feedback(msg) {
getElm('error-nwl').innerHTML = msg;
}
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="checkPass()"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass()" />
<div id="error-nwl">Enter a password of at least 6 characters</div>
答案 10 :(得分:3)
您的问题是检查单个DOM节点的长度,而不是DOM节点值的长度。
您目前所拥有的相当于
Public Function middlebit(startbit, endbit, teststring)
Dim first As Integer
Dim second As Integer
middlebit = ""
If teststring <> "" Then
first = InStr(1, teststring, startbit)
second = InStr(first + Len(startbit), teststring, endbit)
If second = 0 Then second = Len(teststring)
If first > 0 And second > first Then
second = second - first
middlebit = Mid(teststring, first + Len(startbit), second - Len(startbit))
End If
End If
单个DOM节点的长度只有var pass1 = document.getElementById('pass1');
if ( pass1.length > 5 ) {...
,如果找到,则永远不会超过1
。
你想要的是检查值的长度
5
但是你真的想在输入第一个密码字段而不是第二个密码字段时这样做。
使用适当的事件处理程序,更好的检查和消息类,这将是实现它的方法
var pass1 = document.getElementById('pass1');
if ( pass1.value.length > 5 ) {...
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
function msg(_msg, good, time) {
message.innerHTML = _msg;
message.classList.toggle('bad', !good);
message.classList.add('visible');
setTimeout(function() {message.classList.remove('visible')}, time);
}
pass1.addEventListener('input', function() {
this.classList.remove('bad');
this.classList.remove('good');
if (this.value.length > 5) {
this.classList.add('good');
msg("Character number ok!", true, 1800);
}
});
pass1.addEventListener('blur', function() {
if (this.value.length <= 5) {
this.classList.remove('good');
this.classList.add('bad');
msg("You have to enter at least 6 digit!", false, 1800);
} else if (pass1.value !== pass2.value) {
pass2.classList.remove('good');
pass2.classList.add('bad');
msg("Passwords don't match", false, 3000);
}
});
pass2.addEventListener('input', function() {
if (this.value.length > 5) {
var matches = pass1.value === pass2.value;
var _message = matches ? "Passwords match!" : "Passwords don't match";
pass2.classList.toggle('good', matches);
pass2.classList.toggle('bad', !matches);
msg(_message, matches, 3000);
} else {
message.classList.remove('visible');
this.classList.remove('good');
this.classList.remove('bad');
}
});
pass2.addEventListener('blur', function() {
var matches = pass1.value === pass2.value;
if (!matches) {
pass2.classList.remove('good');
pass2.classList.add('bad');
msg("Passwords don't match", matches, 3000);
}
});
#pass1.bad,
#pass2.bad {
background: #ff6666;
}
#pass1.good,
#pass2.good {
background: #66cc66;
}
#error-nwl {
opacity: 0;
color: #66cc66;
transition: opacity 0.3s ease-in-out;
}
#error-nwl.bad {
color: #ff6666;
}
#error-nwl.visible {
opacity: 1;
}
答案 11 :(得分:3)
function checkPassSize(field) {
var pass = document.getElementById(field);
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if (pass.value && pass.value.length > 5) {
pass.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
return true;
} else {
pass.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
return false;
}
}
function checkPass() {
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(checkPassSize('pass1') && checkPassSize('pass2')){
if (pass1.value == pass2.value) {
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
} else {
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
}
}
<input name="password" type="password" placeholder="password"
id="pass1" onkeyup="checkPassSize('pass1');" />
<input name="repeatpassword" type="password"
placeholder="confirm password" id="pass2"
onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
答案 12 :(得分:3)
看来你想做一些事情。
我的建议,
以下代码应该可以满足您的需求。
function checkPass() {
var getTag = Id => document.getElementById(Id);
var pass1 = getTag('pass1');
var pass2 = getTag('pass2');
var message = getTag('error-nwl');
var str;
//Logic that handles Password.
if (!pass1.value)
pass1.removeAttribute('valid');
else if (pass1.value.length < 6) {
pass1.setAttribute('valid', false)
str = " you have to enter at least 6 digit!";
} else {
if (!pass2.value)
str=" character number ok!";
pass1.setAttribute('valid', true);}
//Logic that handles Retype.
if (!pass2.value)
pass2.removeAttribute('valid');
else if (pass1.value != pass2.value) {
pass2.setAttribute('valid', false);
str = " These passwords don't match";
} else
pass2.setAttribute('valid', true);
//Logic that handles the display of message.
message.removeAttribute('valid');
if (pass1.value && pass2.value && !str) {
message.setAttribute('valid', true);
message.innerHTML = "ok!"
} else if (str) {
message.innerHTML = str;
} else
message.innerHTML = '';
return !!message.valid;
}
#pass1[valid=true] {
background: #66cc66
}
#pass1[valid=false] {
background: #ff6666
}
#pass2[valid=true] {
background: #66cc66
}
#pass2[valid=false] {
background: #ff6666
}
#error-nwl {
color: #ff6666
}
#error-nwl[valid=true] {
color: #66cc66
}
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="checkPass()" />
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass()" />
<div id="error-nwl"></div>
答案 13 :(得分:3)
如果您使用的是jQuery,可以使用此jQuery Validation plugin
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Makes "field" required to be the same as #other</title>
<link rel="stylesheet" href="https://jqueryvalidation.org/files/demo/site-demos.css">
</head>
<body>
<form id="myform">
<label for="password">Password</label>
<input id="password" name="password" />
<br/>
<input type="submit" value="Validate!">
</form>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
password: {
minlength: 6,
maxlength: 25,
required: true
}
}
});
</script>
</body>
</html>
答案 14 :(得分:3)
找到已完成更改的添加注释,因为它现在正常工作。
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value == pass2.value){
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
if(pass1.value.length > 5){ ////////just added value here//
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
}
else{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
}
&#13;
<input name="password" type="password" placeholder="password" id="pass1"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
&#13;
答案 15 :(得分:3)
使用以下代码
valid=pass1.value.search(/^[A-Za-z0-9@_]{6,20}$/);
if(valid != 0){
message.innerHTML="Invalid Password.";
}else if(pass1.value.length < 6){
message.innerHTML = " you have to enter at least 6 digit!"
}
答案 16 :(得分:3)
首先,我们要验证三个地方:
我们需要验证服务器端数据的原因(无论其他两个验证有多好)是因为恶意用户可以访问HTML和JavaScript代码,伪造请求或绕过客户端验证其他方式。
如果验证将在服务器端进行,为什么我们需要客户端验证?简短的回答是客户端验证减少了错误提交的数量,因此减少了流量。第二个动机是客户端验证允许更快更容易地向用户提供反馈。
话虽如此,目前的帖子只会处理客户端验证。
现在,为了运行验证代码,我们需要处理适当的事件。在JavaScript中添加事件处理程序的推荐方法是在目标元素上调用addEventListener
。遗憾的是browser support在旧版本的Internet Explorer上并不好用。
因此,我们将从You Might Not Need jQuery中提取代码以添加事件处理程序:
function addEventListener(el, eventName, handler) {
if (el.addEventListener) {
el.addEventListener(eventName, handler);
} else {
el.attachEvent('on' + eventName, function(){
handler.call(el);
});
}
}
注意:attachEvent是Microsoft的专有扩展程序。
现在我们需要决定我们想要处理的事件......
最初的诱惑是处理各个领域的细微变化。这样做的缺点是,只需键入一个字符,系统可能会告诉用户它是错误的(因为值太短,或者其他什么)。这可以解释为输入的单个字符是错误的,然后用户在程序之前停止解析错误。
Luke Wroblewski, "Inline Validation in Web Forms", 2009表示使用&#34;模糊&#34;验证结果的事件(失去焦点)使用户更快地填写表格。
以下是文章的摘录:
(...)当简单问题被标记为“正确”时,参与者感到困惑的事实支持这种解释:
“你是在告诉我我输入了有效的名字或名字吗?”
“这是对格式正确的邮政编码或正确的邮政编码的确认吗?”
这些类型的参与者问题在测试期间引起了一些小问题。我们的参与者知道我们无法知道他们的正确名称或邮政编码,因此他们知道绿色复选标记并不意味着“正确”。但他们认为这意味着什么?他们不确定 - 这就是问题所在。不知道消息的含义,我们的参与者停止向主持人提问,而不是自信地回答那些非常简单的问题。
(...)
当几个参与者在尝试回答问题时发现错误消息时,他们在输入字段中输入了一个附加字符,而不是等待消息更新。如果更新的消息继续显示错误,则他们输入另一个字符,然后等待验证消息再次更新,依此类推,从而导致平均完成时间更长。
(...)
“令你感到沮丧的是,在你向你闪着红光之前,你没有机会把任何东西放进[领域]。”
“当我点击名字字段时,它立即显示[我的名字]太短了。那当然是!我还没开始!“
“我发现当你没有完成打字时,红十字会是多么令人讨厌。这真的让人分心。“
因此,最初的建议是使用blur
事件进行验证。
然而,这带来了另一个问题。如果仅在blur
上进行验证,则当字段的状态设置为无效时,编辑它将继续将其显示为无效 - 直到用户离开该字段。这可能会导致用户想知道他们输入的内容是否仍然存在错误,并且不知道在他们离开现场之前不会进行验证。
为防止出现此问题,我们会为每个字段设置以下状态:
这导致以下状态图:
使用yUML创建的图表。
注意:出于实际目的,Empty
和Validating
可视为等效。在这两种状态中,都没有向用户显示验证状态。此外,当用户重置表单时,应该可以返回Empty
状态(如果给出了这样的选项)。
然后我们有以下内容:
注意:您可以考虑的另一件事是使用timer启动验证,以便在input
,change
和keyup
事件发生一段时间后运行一次。要正确执行此操作,每次运行其中一个事件时,都必须重置此计时器。这是容易出错的代码而且价值不大。
HTML5已经为data form validation添加了各种方法。然而,browser support并不是最好的。这意味着即使我们选择扩展HTML5验证,它也可能无法运行,具体取决于浏览器。
因此,我们将跳过HTML5验证,然后继续添加我们的事件:
function setupValidation(form)
{
addEventHandler(form, 'submit', submitHandler);
var elementIndex = form.elements.length;
while (elementIndex--)
{
addEventHandler (form.elements[elementIndex], 'reset', resetHandler);
addEventHandler (form.elements[elementIndex], 'input', validatingHandler);
addEventHandler (form.elements[elementIndex], 'change', validatingHandler);
addEventHandler (form.elements[elementIndex], 'keyup', validatingHandler);
addEventHandler (form.elements[elementIndex], 'blur', validateHandler);
}
}
现在,鉴于我们只构建表单验证,而不是表单验证框架或库......我们可以获取表单元素和字段来放置我们想要的任何验证。如果我们这样做,那么表单不需要是参数。
要在页面加载时运行我们的代码,我们可以从“你可能不需要jQuery”获取另一个片段:
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fn);
} else {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading')
fn();
});
}
}
现在,我们需要能够存储字段的状态。这可以通过元素对象的自定义属性,属性或类来完成。使用类来标记验证也有助于表单的显示。
验证表单(submitHandler
)时,您必须决定是否要依赖存储的字段验证或再次验证。如果您对依赖于其他字段的字段进行验证,则可能需要将该验证标记为旧验证,这样表单验证代码将知道再次运行验证。无论哪种方式,验证都将通过遍历每个字段来完成。
根据resetHandler
和validatingHandler
,我们的目的是删除valid
和invalid
状态,这是出于前面解释的用户体验原因。
正确完成,不应该向用户提供错误信号。也就是说,代码在有效时绝不应该将该字段显示为无效;当该字段无效时,都不应将该字段显示为有效。
您可能想要禁用HTML5验证。这可以通过向表单添加novalidate
属性来完成。它也可以通过这样的JavaScript来完成:
form.setAttribute('novalidate', 'novalidate');
您可能还想查看字段的属性willValidate
。
如果您想要使用HTML5验证,可以使用函数checkValidity
。
更进一步阅读:Client-Side Form Validation with HTML5和HTML5 Forms: JavaScript and the Constraint Validation API。
另外,文章Constraint Validation: Native Client Side Validation for Web Forms 作者:TJ VanToll有很好的HTML5验证示例。
如果我们要构建一个完整的表单验证库,我们会遇到阅读HTML5验证属性并模仿其行为以便为旧浏览器提供它的麻烦。我们还必须担心如何指定HTML5不提供的其他验证规则(例如检查两个字段是否匹配),而不必为每个案例调整JavaScript代码(因为,正如我所说,那就是我们正在建立一个图书馆。)
可用性建议是内联反馈。也就是在字段旁边添加内联元素,并将反馈作为文本添加。然后,您可以使用CSS或JavaScript使其看起来很花哨。
这个建议的原因是依赖于屏幕阅读器的人会在正确的位置获得反馈。此外,即使CSS被禁用或无法加载,它仍将继续有意义。
这几乎是您使用span
元素所做的事情。每场需要一个。也许整个表单中的一个是你想要把一些 NOT 的消息直接与任何字段相关联。
注意:在阅读字段的值时,我们通常使用field.value
。值的长度为field.value.length
。但应该注意的是,根据输入的类型,读取值的方式会发生变化。对于radio
和checkbox
,请使用field.checked
。对于select
,您需要field.options
(对于可能具有多个值的select
字段,应格外小心)。最后image
,reset
,&#39;按钮&#39;并且submit
没有要检查的值。
你不必这样做!其他人以前做过,你可以从中获取代码! Muahahahah!
这可以通过使用开源库(例如validate.js或我自己的thoth.js)来完成。其他答案已经建议其他图书馆。
你应该能够find more atlernatives。我不假装列出详尽的清单。
重用代码被认为是一种好习惯。您也可以选择研究这些库的代码,以了解它们的工作原理。
我首先要在代码中添加注释:
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
// You start by checking if they match
if(pass1.value == pass2.value){
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}else{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
// And then that messages gets removed by the result of the length check
// Also, pass1.length is undefined
if(pass1.length > 5){
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
}else{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
}
&#13;
<input name="password" type="password" placeholder="password" id="pass1"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
&#13;
相反,您应该按下状态有效,直到另外验证为止:
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
message.style.color = goodColor;
message.innerHTML = "ok!"
if(pass1.value == pass2.value){
pass2.style.backgroundColor = goodColor;
}else{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
if(pass1.value.length > 5){
pass1.style.backgroundColor = goodColor;
}else{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
}
&#13;
<input name="password" type="password" placeholder="password" id="pass1"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
&#13;
除此之外,请注意,如果您将两个字段匹配,然后编辑第一个字段,则该消息不会消失。事实上,编辑第一个消息将永远不会消息,因为我们仍然只检查第二个消息。相反,你可以检查两者。
此外,使用keyup可能会令人讨厌并且令人困惑,您可以考虑使用onblur
来验证用户何时离开该字段(即当该字段失去焦点时,也称为模糊)。
如果你想要更高级的东西,你可以使用keyup方法在用户输入时删除消息,甚至再次检查,但是在每次击键时重置的计时器......
或者你可以使用HTML5验证,因为为什么不呢?
我刚刚更新了我的javascript库thoth以支持minlength验证。还发布了一个帮助库,以便用thoth简化表单验证 - 可能需要根据具体情况进行一些调整,特别是它不包含任何本地化机制。
使用thoth,您可以按如下方式实现代码。注意:如果要将库添加到代码中,请下载库。
Thoth将确保此验证在IE8或更高版本中有效,如果javascript不可用,它将降级为HTML5表单验证。请记住,客户端始终可以操作Javascript和HTML代码,因此请在服务器上重复验证。
.valid
{
color: #66cc66;
}
.invalid
{
color: #ff6666;
}
&#13;
<!DOCTYPE html>
<head>
<title>Demo</title>
<script src="https://rawgit.com/theraot/thoth/master/thoth.js"></script>
<script src="https://rawgit.com/theraot/thoth/master/form_helper.js"></script>
</head>
<form data-on-valid="document.getElementById('ok').style.display='';" data-on-invalid="document.getElementById('ok').style.display='none';" data-lacking="you have to enter at least 6 digit!" data-lacking-class="invalid">
<input name="password" type="password" placeholder="password" id="pass1" minlength="6" required="required"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" minlength="6" data-validate="match(@#pass1)" required="required"/>
</form>
<div id="ok" class="valid" style="display:none">ok!</div>
&#13;
这里有很多data-
属性,我会为你分解:
data-on-valid
:表单验证正确时运行的代码。data-on-invalid
:表单未经验证时将运行的代码。data-lacking
:字符数不足时使用的字符串格式。同样地data-remaining
和data-excess
会在到达maxlength
之前有空间并且文本分别超出maxlength
时有用。data-lacking-class
:用于缺少消息的css类,类似data-remaining-class
和data-excess-class
。以上内容由助手库form_helper.cs
添加。从库thoth
中仅使用以下内容:
data-validate
:其他验证。在这种情况下,它用于添加验证以修改两个字段匹配。很抱歉缺少文档。
注意:data-on-valid
和data-on-invalid
不是正确的事件。
答案 17 :(得分:2)
以下是工作代码..将pass1.length
更改为pass1.value.length
并根据验证更新两个文本字段的颜色。
<html>
<head>
<script>
function checkPass() {
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if (pass1.value == pass2.value) {
pass2.style.backgroundColor = goodColor;
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
} else {
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
if (pass1.value.length > 5 && pass1.value == pass2.value) {
pass1.style.backgroundColor = goodColor;
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
} else {
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
}
</script>
</head>
<body>
<input name="password" type="password" placeholder="password" onkeyup="checkPass();" id="pass1" />
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
</body>
</html>
&#13;
答案 18 :(得分:2)
此代码在输入时验证这两个字段。
<!DOCTYPE html>
<html>
<body>
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="setStyle(this,document.getElementById('pass2'));" />
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="setStyle(this,document.getElementById('pass1'));" />
<div id="error-nwl"></div>
<script>
function isValidLength(element) {
return (element.value.length > 5);
}
function isEqual(element1, element2) {
if (element1.value.length > 0 && element2.value.length > 0)
return (element1.value == element2.value);
return true;
}
function setStyle(element, element2) {
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
var isValidPWD = isValidLength(element) && isEqual(element, element2);
if (isValidPWD) {
if (isValidLength(element)) {
element.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
}
if (isEqual(element, element2)) {
element.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
} else {
if (!isValidLength(element)) {
element.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
if (!isEqual(element, element2)) {
element.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
}
}
</script>
</body>
</html>
答案 19 :(得分:0)
您可以将第二个if else
块移动到第一个if
并获取您可能想要的内容。您还需要将pass1.length
更改为pass1.value.length
。
我还认为你应该检查两个输入框的变化。如果您不这样做,用户可以切换回第一个输入框并在之后更改密码,检查状态将不会更新。
这是更新的代码。
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value.length > 5){
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
//message.innerHTML = "character number ok!"
if(pass1.value == pass2.value) {
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Ok!"
}
else{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "These passwords don't match!"
}
}
else{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "You have to enter at least 6 digits!"
}
}
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="checkPass(); return false;"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass(); return false;" />
<div id="error-nwl"></div>
答案 20 :(得分:0)
你可以使用validform.js。
例如:
<script type="text/javascript" src="http://validform.rjboy.cn/wp-content/themes/validform/js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="http://validform.rjboy.cn/Validform/v5.1/Validform_v5.1_min.js"></script>
<script>
$(".demoform").Validform();
</script>
<form class="demoform">
<input type="password" value="" name="userpassword" datatype="*6-15" errormsg="Password range between 6~15 bits!" />
<input type="password" value="" name="userpassword2" datatype="*" recheck="userpassword" errormsg="The account passwords you entered for the two time were not consistent." /></form>
&#13;
答案 21 :(得分:0)
试试这个!
function resetcol()
{
pass1.style = "";
pass2.style = "";
}
function checkPass()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if (pass1.value == pass2.value && pass1.value.length > 5){
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else{
pass1.style =
message.style.color = badColor;
message.innerHTML = "Bad input. your passwords must match, and be at least 6 characters long."
}
}
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="resetcol();"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="resetcol();" onchange="checkPass(); return false;" />
<div id="error-nwl"></div>
答案 22 :(得分:0)
最好在DOM加载后为代码中的元素分配事件监听器,这样你就可以省略对getElementById的多次调用,但无论如何这是你的代码更正:
var goodColor = "#66cc66", badColor = "#ff6666";
function checkPass() {
message = document.getElementById('error-nwl');
pass1 = document.getElementById('pass1');
pass2 = document.getElementById('pass2');
if (pass1.value.length > 5) {
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "character number ok!"
if (pass2.value == pass1.value) {
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else {
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
}
else {
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
}
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="checkPass()" />
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass()" />
<div id="error-nwl"></div>
答案 23 :(得分:0)
你必须记住事件的多种可能性和事件的顺序。
if(user>0 and user<5){//output username should be 6}
if(pass>0 and pass<5){//output password should be 6}
if(user>5 and pass>5){
if(user==pass){//password match}
else{//invalid password}
}
我修改了您的代码以解决问题
function checkPass() {
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('error-nwl');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if (pass1.value.length > 5) {
pass1.style.backgroundColor = goodColor;
message.style.color = goodColor;
if (pass1.value == pass2.value) {
pass1.style.backgroundColor = goodColor;
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!";
} else {
if (pass2.value.length > 0) {
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match";
}
}
} else {
if (pass1.value.length <= 5 && pass1.value.length > 0) {
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit user!";
if (pass2.value.length > 0) {
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
}
}
if (pass2.value.length <= 5 && pass2.value.length > 0) {
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit pass!"
}
}
}
<html>
<body>
<input name="password" type="password" placeholder="password" onkeyup="checkPass();" id="pass1" />
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass();" />
<div id="error-nwl"></div>
</body>
</html>
这可以通过在两个字段中调用onkeyup方法并编写不同的函数来验证字段来完成,这将确保更大的灵活性并且可以解决大多数情况。您可能还有兴趣添加其他事件,如onBlur,以测试用户获取焦点的时间。
希望这能回答你的问题
答案 24 :(得分:0)
您可以使用两个功能来完成这项工作。
checkPass1()检查天气密码足够长。 checkPass2()检查天气这些密码是否匹配。如果某些用户可能先填写#pass2,我会将checkPass2()添加到checkPass1()中。
function checkPass1()
{
var pass1 = document.getElementById('pass1');
var message = document.getElementById('length-error');
var goodColor = "#66cc66";
var badColor = "#ff6666";
var normalColor = "#ffffff"
if (pass1.value.length <= 5)
{
pass1.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " you have to enter at least 6 digit!"
}
else
{
pass1.style.backgroundColor = normalColor;
message.style.color = goodColor;
message.innerHTML = " the length of password is long enough";
}
checkPass2();
}
function checkPass2()
{
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
var message = document.getElementById('confirm-error');
var goodColor = "#66cc66";
var badColor = "#ff6666";
if(pass1.value == pass2.value)
{
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "ok!"
}
else
{
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = " These passwords don't match"
}
}
&#13;
<input name="password" type="password" placeholder="password" id="pass1" onkeyup="checkPass1()"/>
<input name="repeatpassword" type="password" placeholder="confirm password" id="pass2" onkeyup="checkPass2()" />
<div id="length-error"></div>
<div id="confirm-error"></div>
&#13;