我正在实现在Angular Form register image中注册用户,它之前已经验证过maxlength和minlength。现在,我添加一个验证以检查输入的密码是否有空格。
const form = new FormGroup<UserRegister>({
email: new FormControl<string>(email, [
Validators.required,
Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$')
]),
password: new FormControl<string>(password, [
Validators.required,
Validators.minLength(PASSWORD_MINLENGTH),
Validators.maxLength(PASSWORD_MAXLENGTH),
]),
confirmPassword: new FormControl<string>(confirmPassword, [
Validators.required
]),
}, {validators: [isWhiteSpace, passwordMatchValidator]});
<input matInput type="password" required formControlName="password" [errorStateMatcher]="errorStateMatcher"
placeholder="{{ 'password' | translate }}">
<mat-error *ngIf="form.hasError('required', ['password'])" [translate]="'validation.required'"
[translateParams]="{ value: 'password' | translate }"></mat-error>
<mat-error *ngIf="form.hasError('isWhiteSpace', ['password'])" [translate]="'validation.isWhiteSpace'"
[translateParams]="{ value: 'password' | translate }"></mat-error>
<mat-error *ngIf="form.hasError('minlength', ['password'])" [translate]="'validation.minLength'"
[translateParams]="{ value: 'password' | translate, minLength: PASSWORD_MINLENGTH }"></mat-error>
<mat-error *ngIf="form.hasError('maxlength', ['password'])" [translate]="'validation.maxLength'"
[translateParams]="{ value: 'password' | translate, maxLength: PASSWORD_MAXLENGTH }"></mat-error>
但是当我添加函数isWhiteSpace形成表单时,最小-最大长度的验证未激活。
当我输入一个字符串
答案 0 :(得分:1)
您可以这样做
ngOnInit() {
this.userForm = this.fb.group({
username: ["", noWhitespaceValidator]
});
}
noWhitespaceValidator(control: FormControl) {
const isWhitespace = (control.value || "").trim().length === 0;
const isValid = !isWhitespace;
return of(isValid ? null : { whitespace: true });
}
然后您认为只需使用
*ngIf="userForm.get('username').hasError('whitespace')"