Angular4 FullName字段验证程序无法按预期工作

时间:2017-12-09 14:11:18

标签: html angular typescript

我正在尝试为Angular 4中的注册表单创建一个全名输入字段的自定义验证器,但它没有相应的行为:它显示“仅允许字母和空格”消息,即使它只包含字母和空间。

这是我的验证码:

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

export class FullNameValidator {

  static eachWordShouldBeginWithCapital(control: AbstractControl) : ValidationErrors | null {
    let fullname = control.value as string;
    for(let word of fullname.split(' '))
      if (word[0] == undefined || word[0] == word[0].toLowerCase())
        return {eachWordShouldBeginWithCapital: true};
    return null;

  }

  static onlyAlphabeticalCharactersAndSpaceAllowed(control: AbstractControl) : ValidationErrors | null {
    let regex = '/^[a-zA-Z\\s]*$/';
    if (!(control.value as string).match(regex))
      return {onlyAlphabeticalCharactersAndSpaceAllowed: true};
    return null;
  }
}

这是我的模板:

          <div class="form-group">
            <label class="control-label" for="signupName">Your name</label>
            <input id="signupName" formControlName="fullname" type="text" class="form-control">
          </div>
          <div class="alert alert-danger" *ngIf="fullname.touched && fullname.invalid">
            <div *ngIf="fullname.errors.eachWordShouldBeginWithCapital">Each word should begin with capital letter</div>
            <div *ngIf="fullname.errors.onlyAlphabeticalCharactersAndSpaceAllowed">Only letters and spaces allowed</div>
          </div>

这是我的组件代码:

import {Component, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import {FullNameValidator} from '../../common/validators/fullname-validator';
import {EmailValidators} from '../../common/validators/email-validators';
import {AuthService} from '../../services/data-services/auth.service';


@Component({
  selector: 'register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

  constructor(private authService: AuthService) {
  }

  form = new FormGroup({
    'fullname': new FormControl('', [
      FullNameValidator.eachWordShouldBeginWithCapital,
      FullNameValidator.onlyAlphabeticalCharactersAndSpaceAllowed
    ]),
    'email': new FormControl('', [
      EmailValidators.shouldHaveEmailFormat
    ]),
    'password': new FormControl('', [
      Validators.minLength(6)
    ]),
    'passwordAgain': new FormControl(),
    'dateOfBirth': new FormControl(),
    'gender': new FormControl()
  });

  ngOnInit() {
  }

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

1 个答案:

答案 0 :(得分:1)

您的正则表达式不允许空格。这是因为你\s\\s拼错了^[a-zA-Z\s]*$。 使用这个{{1}}它应该可以工作。