【问题标题】:Angular2 Material : Custom Validation for Angular Material InputAngular2 Material:Angular 材质输入的自定义验证
【发布时间】:2018-03-23 15:21:31
【问题描述】:

在我的 Angular 2 和材料应用程序中,我想检查用户名是否已经被占用。如果它已经被占用,那么它应该会显示错误。

我正在遵循以下指南。
https://material.angular.io/components/input/overview#error-messages

打字稿文件

import {Component} from '@angular/core';
import {FormControl, Validators} from '@angular/forms';

const existingUserNames = ['rohit', 'mohit', 'ronit'];

@Component({
   selector: 'input-errors-example',
   templateUrl: 'input-errors-example.html',
   styleUrls: ['input-errors-example.css'],
})
export class InputErrorsExample {

    emailFormControl = new FormControl('', [
         Validators.required
    ]

    // I want to call below isUserNameTaken function but dont know 
    // how to use it with Validators so that error message will be visible.

    isUserNameTaken() : boolean {
       this.attributeClasses = attributeClasseses;
       this.attributeClasses.find( object => {
           if(object.attributeClass === this.attributeClass) {
               console.log("found " + JSON.stringify(object));
               return true;
           }
       });
       return false;
   }
}

HTML

 <form class="example-form">
   <md-form-field class="example-full-width">
     <input mdInput placeholder="Email [formControl]="emailFormControl">
    <md-error *ngIf="emailFormControl.hasError('required')">
      Email is <strong>required</strong>
    </md-error>

  <!-- I want to make something like that - custom validation -->

     <md-error *ngIf="emailFormControl.hasError('username-already-taken')">
        Username is already taken. Please try another.
    </md-error>
  <!-- custom validation end -->        

     </md-form-field>

【问题讨论】:

标签: typescript error-handling angular2-forms angular-material2


【解决方案1】:

你只需要改变你的函数来接收一个组件作为参数,如果一切正常则返回 null ,否则返回错误对象。然后,将其放在组件验证器的数组中。

// Control declaration
emailFormControl = new FormControl('', [
   Validators.required, 
   isUserNameTaken
]

// Correct validator funcion
isUserNameTaken(component: Component): ValidationErrors {
    this.attributeClasses = attributeClasseses;
    this.attributeClasses.find( object => {
        if(object.attributeClass === this.attributeClass) {
            console.log("found " + JSON.stringify(object));
            // found the username
            return {
                username-already-taken: {
                    username: component.value
                }
            };
        }
    });
    // Everything is ok
    return null;
}

Will Howell 放在 cmets 上的链接中对此进行了更深入的解释。它还解释了如何对非反应形式执行相同的操作。

Tutorial

【讨论】:

    猜你喜欢
    • 2017-10-03
    • 1970-01-01
    • 2020-12-03
    • 2020-09-20
    • 2018-03-18
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2018-01-05
    相关资源
    最近更新 更多