【问题标题】:check if emails match on blur检查电子邮件是否匹配模糊
【发布时间】:2017-06-15 06:39:45
【问题描述】:

我正在尝试检查电子邮件字段和确认电子邮件字段是否相互匹配。也就是说,用户输入他们的电子邮件,然后他们必须再次确认。我希望在模糊时发生匹配/验证(当用户按下回车键或文本字段失去焦点时)。

这是我的 ts 文件:

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
                };
            }
        };
    }
}

这是我的看法:

  <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>

目前,使用它的设置方式,会进行验证,但在输入正确的匹配项时不会被清除。我想知道如何正确设置我的视图?因此,当设置正确匹配而不是设置正确匹配时,将显示/隐藏验证消息。

另外,Form.get('email').length &gt; 0 似乎永远不会大于 0 / 永远不会命中,因此我的标签不会切换为可点击。

我正在使用 Angular 2 和响应式表单。

【问题讨论】:

    标签: html angular typescript angular2-forms


    【解决方案1】:

    看起来您正在混合使用两种表单语法:模板驱动的表单模型驱动的表单

    由于您在班级中使用FormBuilder 声明了一个表单模型,我假设您想要一个模型驱动的表单

    这意味着您的字段不需要像 [(ngModel)]#EmailAddress 这样的属性。

    取而代之的是:

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

    这样写:

    <!-- 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">
    

    您的所有验证器都必须在 FormBuilder 中声明。不只是matchingEmailsValidator,还有required

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

    现在您可以使用以下语法访问字段:

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

    您可以使用这些语法来显示错误。例如:

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

    在上面的示例中,如果触摸了 email 字段(即用户尝试输入内容)并且出现 required 错误,我将显示一条错误消息。

    您还可以通过使用浏览器的开发工具检查表单的标记来验证您的验证规则是否得到执行。 Angular 应该将 .ng-invalid.ng-valid 之类的类添加到具有验证规则的 &lt;input&gt; 标记中。

    最后,关于您检查电子邮件匹配模糊的问题。你不能推迟 Angular 的验证,它会实时发生(当用户输入时)。但您可以等待模糊事件显示错误

    将最后一条建议与我之前的示例相结合,如果电子邮件字段为空并且失去焦点(模糊事件),您应该如何处理错误:

    <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>
    

    在 Euridice 发布 this Plunkr 后更新(01-FEB-2017):

    • 您的模板中仍有大量验证代码。就像我说的,所有验证者都应该在表单模型中声明(使用FormBuilder)。进一步来说:
      • email 字段中的pattern="..." 属性应替换为表单模型中的Validators.pattern()
      • confirmEmail 字段中的validateEqual="email" 属性是什么?你没有在任何地方使用它。
    • 主要问题是您的测试显示错误消息:*ngIf="displayErrors &amp;&amp; !Form.get('email').valid &amp;&amp; Form.get('email').error.mismatch"
      • 首先,属性是带有“s”的errors,而不是error
      • 另外,您的自定义验证器在表单本身上设置错误,而不是在电子邮件字段上。这意味着您应该从 Form.errors.mismatch 而非 Form.get('email').errors.mismatch 检索您的 mismatch 自定义错误。

    这是更新后的工作 Plunkr:https://plnkr.co/edit/dTjcqlm6rZQxA7E0yZLa?p=preview

    【讨论】:

    • 您能否更深入地了解如何使用它:this.Form.get('email').errors?非常感谢您的“迷你教程”。超级有用!
    • 例如如果我想在我的 ts 文件中执行类似操作: if(Form.valid) { this.displayErrors = false; }
    • 我已经修改了我的示例来回答您的评论。如果您认为它可以解决问题,您介意将此答案标记为已接受的答案吗?
    • 我正在尝试找到一种方法来清除表单验证错误消息,因为它出现并且表单现在有效(电子邮件地址匹配)。如何清除错误消息?我正在尝试在 !form.valid 时设置 displayErrors=false 但它没有实时检测到表单的更改。
    • 我更新了视图代码,但 onBlur 仍有问题
    猜你喜欢
    • 2015-04-13
    • 2012-05-16
    • 2016-07-12
    • 2011-10-07
    • 1970-01-01
    • 2014-11-01
    • 2018-02-25
    • 2013-01-05
    • 1970-01-01
    相关资源
    最近更新 更多