在Angular 6中确认密码验证

时间:2018-07-31 05:01:08

标签: angular angular-material angular-forms

我只想使用材料组件执行密码确认密码验证,并在确认密码< / strong>为confirm password field doesn't matchif it is empty字段。尝试了许多无法实现的资源。

也尝试过this video

这是我正在寻找的物质成分

enter image description here

  

HTML

     <mat-form-field >
        <input matInput  placeholder="New password" [type]="hide ? 'password' 
          : 'text'" [formControl]="passFormControl" required>
        <mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' : 
          'visibility_off'}}</mat-icon>
        <mat-error *ngIf="passFormControl.hasError('required')">
            Please enter your newpassword
         </mat-error>
      </mat-form-field>

      <mat-form-field >
         <input matInput  placeholder="Confirm password" [type]="hide ? 
              'password' : 'text'" [formControl]="confirmFormControl" 
                    required>
         <mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' : 
                'visibility_off'}}</mat-icon>
         <mat-error *ngIf="confirmFormControl.hasError('required')">
          Confirm your password
          </mat-error>
      </mat-form-field>
  

TS

     import {Component, OnInit } from '@angular/core';
     import {FormControl, FormGroupDirective, NgForm, Validators} from 
             '@angular/forms';
     import {ErrorStateMatcher} from '@angular/material/core';

     @Component({
            selector: 'asd-set-pass',
            templateUrl: './set-pass.component.html',
             styleUrls: ['./set-pass.component.css']
         })

       passFormControl = new FormControl('', [
            Validators.required,
        ]);
        confirmFormControl = new FormControl('', [
            Validators.required,
            ]);

             hide =true;

       }

正在验证以下条件是否正常 1)如果密码和确认密码字段为空,则显示错误文本。

我想与(.ts)文件中的字段进行比较,例如其如何验证空白字段,如果确认密码字段为空,则会出现错误。

16 个答案:

答案 0 :(得分:49)

可以通过结合以下两个答案来解决此问题:https://stackoverflow.com/a/43493648/6294072https://stackoverflow.com/a/47670892/6294072

因此,首先,您将需要一个自定义的验证器来检查密码,看起来像这样:

checkPasswords(group: FormGroup) { // here we have the 'passwords' group
  let pass = group.controls.password.value;
  let confirmPass = group.controls.confirmPass.value;

  return pass === confirmPass ? null : { notSame: true }     
}

,您将为您的字段创建一个表单组,而不仅仅是两个表单控件,然后为该表单组标记该自定义验证器:

this.myForm = this.fb.group({
  password: ['', [Validators.required]],
  confirmPassword: ['']
}, {validator: this.checkPasswords })

,然后如其他答案所述,mat-error仅显示 FormControl 是否无效,因此您需要一个错误状态匹配器:

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const invalidCtrl = !!(control && control.invalid && control.parent.dirty);
    const invalidParent = !!(control && control.parent && control.parent.invalid && control.parent.dirty);

    return (invalidCtrl || invalidParent);
  }
}
在上面的

中,您可以调整何时显示错误消息。我只会在触摸password字段时显示消息。我也想在上方,从required字段中删除confirmPassword验证器,因为如果密码不匹配,该表单还是无效的。

然后在组件中,创建一个新的ErrorStateMatcher

matcher = new MyErrorStateMatcher();

最后,模板将如下所示:

<form [formGroup]="myForm">
  <mat-form-field>
    <input matInput placeholder="New password" formControlName="password" required>
    <mat-error *ngIf="myForm.hasError('required', 'password')">
        Please enter your new password
    </mat-error>
  </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="Confirm password" formControlName="confirmPassword" [errorStateMatcher]="matcher">
    <mat-error *ngIf="myForm.hasError('notSame')">
        Passwords do not match
    </mat-error>  
  </mat-form-field>
</form>

以下是带有上面代码的演示: StackBlitz

答案 1 :(得分:14)

您可以简单地使用密码字段值作为确认密码字段的模式。 例如:

<div class="form-group">
 <input type="password" [(ngModel)]="userdata.password" name="password" placeholder="Password" class="form-control" required #password="ngModel" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" />
 <div *ngIf="password.invalid && (myform.submitted || password.touched)" class="alert alert-danger">
   <div *ngIf="password.errors.required"> Password is required. </div>
   <div *ngIf="password.errors.pattern"> Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more characters.</div>
 </div>
</div>

<div class="form-group">
 <input type="password" [(ngModel)]="userdata.confirmpassword" name="confirmpassword" placeholder="Confirm Password" class="form-control" required #confirmpassword="ngModel" pattern="{{ password.value }}" />
 <div *ngIf=" confirmpassword.invalid && (myform.submitted || confirmpassword.touched)" class="alert alert-danger">
   <div *ngIf="confirmpassword.errors.required"> Confirm password is required. </div>
   <div *ngIf="confirmpassword.errors.pattern"> Password & Confirm Password does not match.</div>
 </div>
</div>

答案 2 :(得分:3)

如果您不仅拥有“密码”和“验证密码”字段。 这样,“确认密码”字段仅在用户在此字段上写一些内容时才会突出显示错误:

validators.ts

import { FormGroup, FormControl, Validators, FormBuilder, FormGroupDirective, NgForm } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';

export const EmailValidation = [Validators.required, Validators.email];
export const PasswordValidation = [
  Validators.required,
  Validators.minLength(6),
  Validators.maxLength(24),
];

export class RepeatPasswordEStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    return (control && control.parent.get('password').value !== control.parent.get('passwordAgain').value && control.dirty)
  }
}
export function RepeatPasswordValidator(group: FormGroup) {
  let password = group.controls.password.value;
  let passwordConfirmation = group.controls.passwordAgain.value;

  return password === passConfirmation ? null : { passwordsNotEqual: true }     
}

register.component.ts

import { FormGroup, FormControl, Validators, FormBuilder} from '@angular/forms';
import { EmailValidation, PasswordValidation, RepeatPasswordEStateMatcher, RepeatPasswordValidator } from 'validators';

...

form: any;
passwordsMatcher = new RepeatPasswordEStateMatcher;


constructor(private formBuilder: FormBuilder) {
    this.form = this.formBuilder.group ( {
      email: new FormControl('', EmailValidation),
      password: new FormControl('', PasswordValidation),
      passwordAgain: new FormControl(''),
      acceptTerms: new FormControl('', [Validators.requiredTrue])
    }, { validator: RepeatPasswordValidator });
  }

...

register.component.html

<form [formGroup]="form" (ngSubmit)="submitAccount(form)">
    <div class="form-content">
        <div class="form-field">
            <mat-form-field>
            <input matInput formControlName="email" placeholder="Email">
            <mat-error *ngIf="form.get('email').hasError('required')">
                E-mail is mandatory.
            </mat-error>
            <mat-error *ngIf="form.get('email').hasError('email')">
                Incorrect E-mail.
            </mat-error>
            </mat-form-field>
        </div>
        <div class="form-field">
            <mat-form-field>
            <input matInput formControlName="password" placeholder="Password" type="password">
            <mat-hint class="ac-form-field-description">Between 6 and 24 characters.</mat-hint>
            <mat-error *ngIf="form.get('password').hasError('required')">
                Password is mandatory.
            </mat-error>
            <mat-error *ngIf="form.get('password').hasError('minlength')">
                Password with less than 6 characters.
            </mat-error>
            <mat-error *ngIf="form.get('password').hasError('maxlength')">
                Password with more than 24 characters.
            </mat-error>
            </mat-form-field>
        </div>
        <div class="form-field">
            <mat-form-field>
            <input matInput formControlName="passwordAgain" placeholder="Confirm the password" type="password" [errorStateMatcher]="passwordsMatcher">
            <mat-error *ngIf="form.hasError('passwordsNotEqual')" >Passwords are different. They should be equal!</mat-error>
            </mat-form-field>
        </div>
        <div class="form-field">
            <mat-checkbox name="acceptTerms" formControlName="acceptTerms">I accept terms and conditions</mat-checkbox>
        </div>
    </div>
    <div class="form-bottom">
        <button mat-raised-button [disabled]="!form.valid">Create Account</button>
    </div>
</form>

我希望对您有帮助!

答案 3 :(得分:1)

我正在使用角度6,并且一直在寻找匹配密码和确认密码的最佳方法。这也可以用于匹配表单中的任何两个输入。我使用了角度指令。我一直想使用它们

  

ng g d比较验证器--spec false   我将被添加到您的模块中。下面是指令

import { Directive, Input } from '@angular/core';
import { Validator, NG_VALIDATORS, AbstractControl, ValidationErrors } from '@angular/forms';
import { Subscription } from 'rxjs';

@Directive({
  // tslint:disable-next-line:directive-selector
  selector: '[compare]',
  providers: [{ provide: NG_VALIDATORS, useExisting: CompareValidatorDirective, multi: true}]
})
export class CompareValidatorDirective implements Validator {
  // tslint:disable-next-line:no-input-rename
  @Input('compare') controlNameToCompare;

  validate(c: AbstractControl): ValidationErrors | null {
    if (c.value.length < 6 || c.value === null) {
      return null;
    }
    const controlToCompare = c.root.get(this.controlNameToCompare);

    if (controlToCompare) {
      const subscription: Subscription = controlToCompare.valueChanges.subscribe(() => {
        c.updateValueAndValidity();
        subscription.unsubscribe();
      });
    }

    return controlToCompare && controlToCompare.value !== c.value ? {'compare': true } : null;
  }

}

现在在您的组件中

<div class="col-md-6">
              <div class="form-group">
                <label class="bmd-label-floating">Password</label>
                <input type="password" class="form-control" formControlName="usrpass" [ngClass]="{ 'is-invalid': submitAttempt && f.usrpass.errors }">
                <div *ngIf="submitAttempt && signupForm.controls['usrpass'].errors" class="invalid-feedback">
                  <div *ngIf="signupForm.controls['usrpass'].errors.required">Your password is required</div>
                  <div *ngIf="signupForm.controls['usrpass'].errors.minlength">Password must be at least 6 characters</div>
                </div>
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label class="bmd-label-floating">Confirm Password</label>
                <input type="password" class="form-control" formControlName="confirmpass" compare = "usrpass"
                [ngClass]="{ 'is-invalid': submitAttempt && f.confirmpass.errors }">
                <div *ngIf="submitAttempt && signupForm.controls['confirmpass'].errors" class="invalid-feedback">
                  <div *ngIf="signupForm.controls['confirmpass'].errors.required">Your confirm password is required</div>
                  <div *ngIf="signupForm.controls['confirmpass'].errors.minlength">Password must be at least 6 characters</div>
                  <div *ngIf="signupForm.controls['confirmpass'].errors['compare']">Confirm password and Password dont match</div>
                </div>
              </div>
            </div>

我希望这对您有帮助

答案 4 :(得分:1)

*此解决方案适用于反应形式

您可能已经听说过确认密码,称为跨场验证。虽然我们通常编写的字段级别验证器只能应用于单个字段。对于跨域验证,您可能必须编写一些父级验证器。对于确认密码的具体情况,我宁愿:

this.form.valueChanges.subscribe(field => {
  if (field.password !== field.confirm) {
    this.confirm.setErrors({ mismatch: true });
  } else {
    this.confirm.setErrors(null);
  }
});

这是模板:

<mat-form-field>
      <input matInput type="password" placeholder="Password" formControlName="password">
      <mat-error *ngIf="password.hasError('required')">Required</mat-error>
</mat-form-field>
<mat-form-field>
    <input matInput type="password" placeholder="Confirm New Password" formControlName="confirm">`enter code here`
    <mat-error *ngIf="confirm.hasError('mismatch')">Password does not match the confirm password</mat-error>
</mat-form-field>

答案 5 :(得分:1)

我在AJT_82的答案中发现了一个错误。由于我没有足够的声誉来评论AJT_82的答案,因此我必须在此答案中发布错误和解决方案。

以下是错误:

enter image description here

解决方案:在以下代码中:

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const invalidCtrl = !!(control && control.invalid && control.parent.dirty);
    const invalidParent = !!(control && control.parent && control.parent.invalid && control.parent.dirty);

    return (invalidCtrl || invalidParent);
  }
}

control.parent.invalid更改为control.parent.hasError('notSame')将解决此问题。

小改动后,问题解决了。

enter image description here

答案 6 :(得分:0)

我建议使用库ng-form-rules。它是一个了不起的库,用于创建各种形式的表单,并具有与组件分离的验证逻辑(并且可重复使用)。它们具有great documentationexamplesvideo that show a bunch of its functionality。进行这样的验证(检查两个表单控件的相等性)很简单。

您可以check out their README获取一些高级信息和基本示例。

答案 7 :(得分:0)

我的回答很简单>我已经创建了密码,并使用drivingn角度为6的模板来确认密码验证

我的html文件

<div class="form-group">
  <label class="label-sm">Confirm Password</label>
  <input class="form-control" placeholder="Enter Password" type="password" #confirm_password="ngModel" [(ngModel)]="userModel.confirm_password" name="confirm_password" required (keyup)="checkPassword($event)" />
  <div *ngIf="confirm_password.errors && (confirm_password.dirty||confirm_password.touched||signup.submitted)">
  <div class="error" *ngIf="confirm_password.errors.required">Please confirm your password</div>
  </div>
  <div *ngIf="i" class='error'>Password does not match</div>
</div>

我的打字稿文件

      public i: boolean;

      checkPassword(event) {
        const password = this.userModel.password;
        const confirm_new_password = event.target.value;

        if (password !== undefined) {
          if (confirm_new_password !== password) {
            this.i = true;
          } else {
            this.i = false;
          }
        }
      }

当我点击“提交”按钮时,我会检查i的值为真还是假

如果是

if (this.i) {
      return false;
    }

else{
**form submitted code comes here**
}

答案 8 :(得分:0)

我只需很少的代码就可以将责任委派给Submit事件。

<div class="form-label-group">
    <input type="password" id="inputPassword" class="form-control" (change)="StorePassword($event)" required>
    <label for="inputPassword">Password</label>
</div>

<div class="form-label-group">
    <input type="password" id="inputConfirmaPassword" class="form-control" (invalid)="GetInvalidMessage($event)"
    [pattern]="iPassword" required>
    <label for="inputConfirmaPassword">Confirm password</label>
</div>

我在确认输入中创建一个与密码相同的模式(由于密码输入的change事件,将密码存储在变量中)。

iPassword: string = null;

StorePassword ( event: any ): void {
    this.iPassword = event.target.value != '' ? event.target.value : null;
}

可以通过以下方式自定义错误消息:

GetInvalidMessage ( event: any ): void {
    if ( event.target.validity.patternMismatch && event.target.id == 'inputConfirmaPassword' ) {
        event.target.setCustomValidity( "Passwords do not match" );
    }
}

答案 9 :(得分:0)

我是这样做的。希望对您有帮助。

HTML:

<form [formGroup]='addAdminForm'>   
          <div class="form-group row">
            <label class="col-sm-3 col-form-label">Password</label>
            <div class="col-sm-7">
              <input type="password" class="form-control" formControlName='password' (keyup)="checkPassSame()">

              <div *ngIf="addAdminForm.controls?.password?.invalid && addAdminForm.controls?.password.touched">
                <p *ngIf="addAdminForm.controls?.password?.errors.required" class="errorMsg">*This field is required.</p>
              </div>
            </div>
          </div>

          <div class="form-group row">
            <label class="col-sm-3 col-form-label">Confirm Password</label>
            <div class="col-sm-7">
              <input type="password" class="form-control" formControlName='confPass' (keyup)="checkPassSame()">

              <div *ngIf="addAdminForm.controls?.confPass?.invalid && addAdminForm.controls?.confPass.touched">
                <p *ngIf="addAdminForm.controls?.confPass?.errors.required" class="errorMsg">*This field is required.</p>
              </div>
              <div *ngIf="passmsg != '' && !addAdminForm.controls?.confPass?.errors?.required">
                <p class="errorMsg">*{{passmsg}}</p>
              </div>  
            </div>
          </div>
      </form>

TS文件:

export class AddAdminAccountsComponent implements OnInit {

  addAdminForm: FormGroup;
  password: FormControl;
  confPass: FormControl;
  passmsg: string;


  constructor(
    private http: HttpClient,
    private router: Router,
  ) { 
  }

  ngOnInit() {    
    this.createFormGroup();
  }



    // |---------------------------------------------------------------------------------------
    // |------------------------ form initialization -------------------------
    // |---------------------------------------------------------------------------------------
    createFormGroup() {    
      this.addAdminForm = new FormGroup({
        password: new FormControl('', [Validators.required]),
        confPass: new FormControl('', [Validators.required]),
      })
    }



    // |---------------------------------------------------------------------------------------
    // |------------------------ Check method for password and conf password same or not -------------------------
    // |---------------------------------------------------------------------------------------

    checkPassSame() {
      let pass = this.addAdminForm.value.password;
      let passConf = this.addAdminForm.value.confPass;
      if(pass == passConf && this.addAdminForm.valid === true) {
        this.passmsg = "";
        return false;
      }else {
        this.passmsg = "Password did not match.";
        return true;
      }
    }



}

答案 10 :(得分:0)

最简单的imo:

(例如,它也可以用于电子邮件)

public static matchValues(
    matchTo: string // name of the control to match to
  ): (AbstractControl) => ValidationErrors | null {
    return (control: AbstractControl): ValidationErrors | null => {
      return !!control.parent &&
        !!control.parent.value &&
        control.value === control.parent.controls[matchTo].value
        ? null
        : { isMatching: false };
    };
}

在您的组件中:

this.SignUpForm = this.formBuilder.group({

password: [undefined, [Validators.required]],
passwordConfirm: [undefined, 
        [
          Validators.required,
          matchValues('password'),
        ],
      ],
});

答案 11 :(得分:0)

只需执行一个标准的自定义验证器,然后首先验证是否定义了表单本身,否则将引发一个错误,指出该表单未定义,因为在构造表单之前,它将首先尝试运行验证器。

// form builder
private buildForm(): void {
    this.changePasswordForm = this.fb.group({
        currentPass: ['', Validators.required],
        newPass: ['', Validators.required],
        confirmPass: ['', [Validators.required, this.passwordMatcher.bind(this)]],
    });
}

// confirm new password validator
private passwordMatcher(control: FormControl): { [s: string]: boolean } {
    if (
        this.changePasswordForm &&
        (control.value !== this.changePasswordForm.controls.newPass.value)
    ) {
        return { passwordNotMatch: true };
    }
    return null;
}

它只是检查新密码字段与确认密码字段具有相同的值。是针对确认密码字段而非整个表单的验证器。

您只需要验证是否定义了this.changePasswordForm,否则在构建表单时它将引发未定义的错误。

它工作得很好,无需创建指令或错误状态匹配器。

答案 12 :(得分:0)

不必使用嵌套表单组和自定义ErrorStateMatcher来确认密码验证。添加了这些步骤以促进密码字段之间的协调,但是您可以这样做,而无需所有开销。

这里是一个例子:

this.registrationForm = this.fb.group({
  username: ['', Validators.required],
  email: ['', [Validators.required, Validators.email]],
  password1: ['', [Validators.required, (control) => this.validatePasswords(control, 'password1') ] ],
  password2: ['', [Validators.required, (control) => this.validatePasswords(control, 'password2') ] ]
});

请注意,我们正在将其他上下文传递给validatePasswords方法(无论源是password1还是password2)。

  validatePasswords(control: AbstractControl, name: string) {
    if (this.registrationForm === undefined || this.password1.value === '' || this.password2.value === '') {
      return null;
    } else if (this.password1.value === this.password2.value) {
      if (name === 'password1' && this.password2.hasError('passwordMismatch')) {
        this.password1.setErrors(null);
        this.password2.updateValueAndValidity();
      } else if (name === 'password2' && this.password1.hasError('passwordMismatch')) {
        this.password2.setErrors(null);
        this.password1.updateValueAndValidity();
      }
      return null;
    } else {
      return {'passwordMismatch': { value: 'The provided passwords do not match'}};
    }  

请注意,当密码匹配时,我们将与其他密码字段进行协调以更新其验证。这将清除所有过时的密码不匹配错误。

出于完整性考虑,下面是定义this.password1this.password2的getter。

  get password1(): AbstractControl {
    return this.registrationForm.get('password1');
  }

  get password2(): AbstractControl {
    return this.registrationForm.get('password2');
  }

答案 13 :(得分:0)

反应式的单一方法

TYPESCRIPT

// All is this method
onPasswordChange() {
  if (this.confirm_password.value == this.password.value) {
    this.confirm_password.setErrors(null);
  } else {
    this.confirm_password.setErrors({ mismatch: true });
  }
}

// getting the form control elements
get password(): AbstractControl {
  return this.form.controls['password'];
}

get confirm_password(): AbstractControl {
  return this.form.controls['confirm_password'];
}

HTML

// PASSWORD FIELD
<input type="password" formControlName="password" (change)="onPasswordChange()" />

// CONFIRM PASSWORD FIELD
<input type="password" formControlName="confirm_password" (change)="onPasswordChange()" />

// SHOW ERROR IF MISMATCH
<span *ngIf="confirm_password.hasError('mismatch')">Password do not match.</span>

答案 14 :(得分:0)

Angular中的反应形式使我们非常容易地定义自定义验证器。在本教程中,我将创建确认密码验证。为此,我将使用必须匹配的名称创建一个单独的文件夹,并将我的自定义验证程序文件保存在该文件夹中。我将其命名为validate-password angular .ts,因此听起来通用。 必须匹配> validate-password.ts

import { AbstractControl } from '@angular/forms';
export class ValidatePassword {
  static MatchPassword(abstractControl: AbstractControl) {
    let password = abstractControl.get('password').value;
    let confirmPassword = abstractControl.get('confirmPassword').value;
     if (password != confirmPassword) {
         abstractControl.get('confirmPassword').setErrors({
           MatchPassword: true
         })
    } else {
      return null
    }
  }

}

您可以在这里看到:Confirm password Validation angular

答案 15 :(得分:0)

您可以使用这种方式来满足此要求。我使用以下方法来验证密码和确认密码。

要使用此方法,您必须从FormGroup库中导入 @angular/forms

import { FormBuilder, Validators, FormGroup } from '@angular/forms';

FormBuilder组

this.myForm= this.formBuilder.group({
  password    : ['', Validators.compose([Validators.required])],
  confirmPassword    : ['',  Validators.compose([Validators.required])],
},
{validator: this.checkPassword('password', 'confirmPassword') }
);

验证两个字段的方法

 checkPassword(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 another validator has already found an error on the matchingControl
            return;
        }
        // set error on matchingControl if validation fails
        if (control.value !== matchingControl.value) {
            matchingControl.setErrors({ mustMatch: true });
            this.isPasswordSame = (matchingControl.status == 'VALID') ? true : false;
        } else {
            matchingControl.setErrors(null);
            this.isPasswordSame = (matchingControl.status == 'VALID') ? true : false;
        }
    }
  }

HTML : 在这里,我使用个性化的 isPasswordSame 变量,您可以使用内置的hasError或任何其他变量。

<form [formGroup]="myForm">
  <ion-item>
    <ion-label position="floating">Password</ion-label>
    <ion-input required type="text" formControlName="password" placeholder="Enter Password"></ion-input>
  </ion-item>
  <ion-label *ngIf="myForm.controls.password.valid">
      <p class="error">Please enter password!!</p>
  </ion-label>
  <ion-item>
    <ion-label position="floating">Confirm Password</ion-label>
    <ion-input required type="text" formControlName="confirmPassword" placeholder="Enter Confirm Password"></ion-input>
  </ion-item>
  <ion-label *ngIf="isPasswordSame">
      <p class="error">Password and Confrim Password must be same!!</p>
  </ion-label>
</form>