Javascript 检查密码和确认密码是否相同的验证不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3093176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validation to check if password and confirm password are same is not working
提问by bhavna raghuvanshi
Here's my code:
这是我的代码:
function validate_form(thisform)
{
with (thisform)
{
if (validate_required(name,"Name must be filled out!")==false)
{name.focus();return false;}
if (validate_required(country," Country must be filled out!")==false)
{country.focus();return false;}
if (validate_required(state,"State must be filled out!")==false)
{state.focus();return false;}
if (validate_required(city,"City must be filled out!")==false)
{city.focus();return false;}
if (validate_required(contact,"Contact must be filled out!")==false)
{contact.focus();return false;}
if (validate_required(emailid,"Email must be filled out!")==false)
{emailid.focus();return false;}
if (validate_email(userid,"Email is not valid")==false)
{userid.focus();return false;}
if (validate_required(password,"pasword must be filed out")==false)
{password.focus();return false;}
if (validate_required(cpassword,"Password must be confirmed")==false)
{cpassword.focus();return false;}
if(validate_required((password.value != cpassword.value),"Your password and confirmation password do not match.")==false) {
cpassword.focus();return false;
}
All other validations are working but not the last one. Why is that so and how to fix it?
所有其他验证都有效,但不是最后一个。为什么会这样以及如何解决它?
回答by DmitryK
I presume you've got validate_required() function from this page: http://www.w3schools.com/js/js_form_validation.asp?
我想你已经从这个页面获得了 validate_required() 函数:http: //www.w3schools.com/js/js_form_validation.asp?
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}
In this case your last condition will not work as you expect it.
在这种情况下,您的最后一个条件将不会像您期望的那样工作。
You can replace it with this:
你可以用这个替换它:
if (password.value != cpassword.value) {
alert("Your password and confirmation password do not match.");
cpassword.focus();
return false;
}
回答by Lasse Reichstein
The validate_required function seems to expect an HTML form control (e.g, text input field) as first argument, and check whether there is a value there at all. That is not what you want in this case.
validate_required 函数似乎期望一个 HTML 表单控件(例如,文本输入字段)作为第一个参数,并检查那里是否有值。在这种情况下,这不是您想要的。
Also, when you write ['password'].value, you create a new array of length one, containing the string'password', and then read the non-existing property "value"from it, yielding the undefined value.
此外,当您编写 时['password'].value,您会创建一个长度为 1 的新数组,其中包含string'password',然后"value"从中读取不存在的属性,从而产生未定义的值。
What you may want to try instead is:
您可能想要尝试的是:
if (password.value != cpassword.value) { cpassword.focus(); return false; }
(You also need to write the error message somehow, but I can't see from your code how that is done.).
(您还需要以某种方式编写错误消息,但我无法从您的代码中看到这是如何完成的。)。
回答by asish rauto
function validate()
{
var a=documents.forms["yourformname"]["yourpasswordfieldname"].value;
var b=documents.forms["yourformname"]["yourconfirmpasswordfieldname"].value;
if(!(a==b))
{
alert("both passwords are not matching");
return false;
}
return true;
}
回答by Shrayas Suryakumar
if((pswd.length<6 || pswd.length>12) || pswd == ""){
document.getElementById("passwordloc").innerHTML="character should be between 6-12 characters"; status=false;
}
else {
if(pswd != pswdcnf) {
document.getElementById("passwordconfirm").innerHTML="password doesnt matched"; status=true;
} else {
document.getElementById("passwordconfirm").innerHTML="password matche";
document.getElementById("passwordloc").innerHTML = '';
}
}
}
回答by Deepak Jha
Step 1 :
第1步 :
Create ts : app/_helpers/must-match.validator.ts
创建 ts : app/_helpers/must-match.validator.ts
import { FormGroup } from '@angular/forms';
export function MustMatch(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.mustMatch) {
return;
}
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
} else {
matchingControl.setErrors(null);
}
}
}
Step 2 :
第2步 :
Use in your component.ts
在你的 component.ts 中使用
import { MustMatch } from '../_helpers/must-match.validator';
ngOnInit() {
this.loginForm = this.formbuilder.group({
Password: ['', [Validators.required, Validators.minLength(6)]],
ConfirmPassword: ['', [Validators.required]],
}, {
validator: MustMatch('Password', 'ConfirmPassword')
});
}
Step 3 :
第 3 步:
Use In View/Html
在视图/Html 中使用
<input type="password" formControlName="Password" class="form-control" autofocus>
<div *ngIf="loginForm.controls['Password'].invalid && (loginForm.controls['Password'].dirty || loginForm.controls['Password'].touched)" class="alert alert-danger">
<div *ngIf="loginForm.controls['Password'].errors.required">Password Required. </div>
<div *ngIf="loginForm.controls['Password'].errors.minlength">Password must be at least 6 characters</div>
</div>
<input type="password" formControlName="ConfirmPassword" class="form-control" >
<div *ngIf="loginForm.controls['ConfirmPassword'].invalid && (loginForm.controls['ConfirmPassword'].dirty || loginForm.controls['ConfirmPassword'].touched)" class="alert alert-danger">
<div *ngIf="loginForm.controls['ConfirmPassword'].errors.required">ConfirmPassword Required. </div>
<div *ngIf="loginForm.controls['ConfirmPassword'].errors.mustMatch">Your password and confirmation password do not match.</div>
</div>

