Check if blur letters match

I am trying to check if the email fields match and confirm that the email fields match. That is, the user enters them into his email address, and then must confirm it again. I want the match / check to be done when blurring (when the user presses the enter button or the text field loses focus).

Here is my ts file:

import {Component, OnInit} from '@angular/core'; import {User} from './user.interface'; import {FormBuilder, FormGroup, ValidatorFn} from '@angular/forms'; @Component({ selector: 'my-email', templateUrl: '/app/components/profile/email.component.html', styleUrls:['styles.css'], }) export class EmailComponent implements OnInit { public user : User; Form : FormGroup; ngOnInit() { // initialize model here this.user = { Email: '', confirmEmail: '' } if(this.Form.valid) { this.displayErrors = false; } } constructor(fb: FormBuilder, private cookieService: CookieService, private router: Router) { this.Form = fb.group({ email: [''], confirmEmail: [''] }, { validator: this.matchingEmailsValidator('email', 'confirmEmail') }); } save(model: User, isValid: boolean) { // call API to save customer //save email } matchingEmailsValidator(emailKey: string, confirmEmailKey: string): ValidatorFn { return (group: FormGroup): {[key: string]: any} => { let email = group.controls[emailKey]; let confirmEmail = group.controls[confirmEmailKey]; if (email.value !== confirmEmail.value) { return { mismatch: true }; } }; } } 

Here is my view:

  <form [formGroup]="Form" novalidate (ngSubmit)="Form.valid && save(Form.value, Form.valid)"> <div class="container-fluid"> <div id = "container" class="contain" style="text-align: center"> <div> <fieldset class="form-group"> <label id = "rounded" class="item item-input .col-md-6 .col-md-offset-3"> <input class="email-address-entry form-control" name="email" type="email" placeholder=" name@domain.com " formControlName="email" pattern="^(\\w|[0-9.!#$%&'*+/=?^_\`{|}~-]) +@ (\\w|[0-9-])+(?:‌​[.](\\w|[0-9-])+)*$"/> </label> <p class="Reenter-your-email">Reenter your email to confirm</p> <label id = "rounded" class="item item-input"> <input class="email-address-entry form-control" (blur)="displayErrors=true" name="confirmEmail" type="email" placeholder=" name@domain.com " formControlName="confirmEmail" validateEqual="email"/> </label> </fieldset> </div> <div> <label class="entry-invalid"> <p *ngIf="displayErrors && !Form.get('email').valid">The email you entered does not match.</p> </label> </div> <div (click)="Form.get('email').length > 0 ? save(Form.value, Form.valid) : NaN" class="{{ Form.get('email').length > 0 ? 'container-fluid anchorBottomHighlight' : 'container-fluid anchorBottom'}}"> <label class="footerLabel">Confirm</label> </div> </div> </div> </form> 

Currently, when it is configured, a check is performed, but it is not cleared when the correct match is entered. I am wondering how can I properly adjust my opinion? Thus, the validation message is displayed / hidden when the correct match is established, not.

It also seems like Form.get('email').length > 0 never greater than 0 / never hits, so my label doesn't switch so that it can be clicked.

I am using Angular 2 and reactive forms.

+6
source share
1 answer

You seem to be mixing two form syntaxes: form-driven forms and model-driven forms.

Since you are declaring a form model in your class with FormBuilder , I assume that you want a model-driven form.

This means that your fields do not need attributes such as [(ngModel)] or #EmailAddress .

Instead of this:

 <input type="email" [(ngModel)]="user.EmailAddress" required #EmailAddress="ngModel"> 

Write this:

 <!-- Now I'm using `formControlName` to bind the field to the model --> <!-- Its value must match one of the names you used in the FormBuilder --> <input type="email" formControlName="email"> 

ALL of your validators must be declared in FormBuilder. Not only matchingEmailsValidator , but also required :

 this.Form = fb.group({ email: ['', Validators.required], confirmEmail: ['', Validators.required] }, { validator: this.matchingEmailsValidator('email', 'confirmEmail') }); 

Now you can access the field with the following syntax:

 // In the class this.Form.get('email').value this.Form.get('email').errors 
 <!-- In the template --> {{ Form.get('email').value }} {{ Form.get('email').errors }} 

You can use these syntaxes to display errors. For instance:

 <input type="email" formControlName="email"> <p *ngIf="Form.get('email').dirty && Form.get('email').errors.required"> This field is required. </p> 

In the above example, an error message appears if the email field has been touched (i.e. the user tried to enter something) And a required error is present.

You can also verify that your validation rules are being followed by checking the layout of the form using your browser tools. Angular should add tags .ng-invalid or .ng-valid to tags <input> , which have validation rules.

Finally, regarding your question, check the correspondence by email when blurring . You cannot postpone Angular validation, this will happen in real time (as the user enters). But you can wait for the blur event to display errors .

Combining this last tip with my previous example, here is how you might be mistaken if the email field is empty and it has lost focus (blur event):

 <input type="email" formControlName="email" (blur)="displayErrors=true"> <p *ngIf="displayErrors && Form.get('email').dirty && Form.get('email').errors.required"> This field is required. </p> 

UPDATE (01-FEB-2017) after the publication of Euridice this Plunkr :

  • You still have wayyyyy for the great validation code in your template. As I said, ALL VALIDATORS must be declared in the FORM MODEL (with FormBuilder ). More specific:
    • The pattern="..." attribute in the email field should be replaced with Validators.pattern() in the form model.
    • What is the validateEqual="email" attribute in the confirmEmail field? You are not using anything.
  • The main problem is that your test displays an error message: *ngIf="displayErrors && !Form.get('email').valid && Form.get('email').error.mismatch" .
    • First of all, the errors property with "s", not error .
    • In addition, your custom validator sets an error in the form itself , and not in the email field. This means that you should get a custom error mismatch of Form.errors.mismatch , the NOT Form.get('email').errors.mismatch .

Here's the updated, working Plunkr: https://plnkr.co/edit/dTjcqlm6rZQxA7E0yZLa?p=preview

+4
source

Source: https://habr.com/ru/post/1014544/


All Articles