无法读取自定义验证程序的属性,并且必填-Angular

时间:2018-09-01 18:11:37

标签: javascript angular

我尝试制作自定义验证程序,当用户在文本上留出空格时会向用户发送消息,但我收到此错误。

  • 1-无法读取未定义的属性'removeSpaceFromUserName'
  • 2-无法读取null的“必需”属性    在Object.eval [作为updateDirectives]

这是组件的html

    <form [formGroup]='form'>
        <div class="form-group">
            <label for="username">Username</label>
            <input 
                formControlName='username'
                id="username" 
                type="text" 
                class="form-control">
                <div *ngIf="username.touched && username.touched"  class="alert alert-danger">
                     <div *ngIf="username.errors.required"> You need to enter user name</div>
                     <div *ngIf="username.errors.minlength"> Min Length is 
                        {{ username.errors.minLength.requiredLength}}
                        </div>
                      <div *ngIf="UserNameValiditors.removeSpaceFromUserName">
                           removeSpaceFromUserName </div>   
                </div>
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <input 
                formControlName='password'
                id="password" 
                type="text" 
                class="form-control">
        </div>
        <button class="btn btn-primary" type="submit">Sign Up</button>
    </form>

这是自定义验证器类

import { AbstractControl, ValidationErrors } from "@angular/forms";

export class UserNameValiditors {
    static removeSpaceFromUserName(control: AbstractControl): ValidationErrors | null {
        if ((control.value as string).indexOf(' ') >= 0) {
            return {
                removeSpaceFromUserName: true
            };
        }
        else {
            return null;
        }
    }
}

import { Component } from '@angular/core';
import { FormControl , FormGroup , Validators } from "@angular/forms";
import { UserNameValiditors } from './UserNameValditors';

@Component({
  selector: 'signup-form',
  templateUrl: './signup-form.component.html',
  styleUrls: ['./signup-form.component.css']
})
export class SignupFormComponent {

  form= new FormGroup(
    {
       username  : new FormControl('',
      [
        Validators.required,
        Validators.minLength(3) ,
        UserNameValiditors.removeSpaceFromUserName
      ]) ,
       password  : new FormControl('',Validators.required)
    });

    get username()
    {
      return this.form.get('username');
    }
  
}

2 个答案:

答案 0 :(得分:0)

使用hasError()检查表单上是否存在某些错误。

html代码

<div *ngIf="username.hasError('required')"> You need to enter user name</div>
            <div *ngIf="username.hasError('minlength')"> Min Length is {{ username.hasError('minLength')}}
            </div>f
            <div *ngIf="username.hasError('removeSpaceFromUserName')">
                removeSpaceFromUserName </div>
</div>

您的工作代码为here

答案 1 :(得分:0)

您可以尝试使用此解决方案。

我已在 Stackblitz

上创建了一个演示

app.component.ts

myForms: FormGroup;

  constructor(fb: FormBuilder) {

    this.myForms = fb.group({
      username: [null, Validators.compose([
        Validators.required, Validators.minLength(3), usernameValidator])],
      password: [null, [
        Validators.required]]
    });
  }

app.component.html

<form [formGroup]="myForms">

    <label>User Name : 
        <input type="text"  formControlName="username">
    </label><br>

    <div class="errors" *ngIf="myForms.get('username').invalid && (myForms.get('username').touched || myForms.get('username').dirty)">

        <div *ngIf="myForms.get('username').hasError('required')">
            username is required
        </div>

        <div *ngIf="myForms.get('username').errors.minlength">
            username must be at least 3 characters
        </div>

        <div class="error-text" *ngIf="myForms.get('username').hasError('removeSpaceFromUserName')">
            removeSpaceFromUserName  
        </div>
    </div>

  <div class="form-group">
            <label for="password">Password</label>
            <input 
                formControlName='password'
                id="password" 
                type="text" 
                class="form-control">
        </div>
        <button class="btn btn-primary" type="submit">Sign Up</button>
</form>