在角度代码中使用反应形式。有写在单独的文件
noWhiteSpaceValidator ,此文件随后包含在 .ts 文件和 .html 文件
中的formControl中这是验证器的代码:
import { FormControl } from '@angular/forms';
export function noWhiteSpaceValidator(control: FormControl) {
if (control.value === null || control.value === '') {
return null;
}
const isWhitespace = control.value.trim().length === 0;
const isValid = !isWhitespace;
return isValid ? null : { whitespace: true };
}
.ts文件的一部分:
import { FormGroup, FormControl, Validators, AbstractControl } from '@angular/forms';
import { noWhiteSpaceValidator} from '...';
export class UserProfileFormComponent implements OnInit {
user: User;
private userProfileForm: FormGroup;
private firstNameFormControl = new FormControl('', [Validators.required, noWhiteSpaceValidator]);
private lastNameFormControl = new FormControl('', [Validators.required, noWhiteSpaceValidator]);
ngOnInit() {
this.userProfileForm = new FormGroup({
first_name: this.firstNameFormControl,
last_name: this.lastNameFormControl,
和.html文件的一部分:
<form [formGroup]="userProfileForm">
...
<div class="form-group">
<label for="id">{{ 'userProfile.firstName' | translate }}</label>
<input type="text" class="form-control" [minLength]="2
[maxLength]="100" formControlName="first_name"
required noWhiteSpaceValidator>
<div *ngIf="firstNameFormControl.errors">
<div *ngIf="firstNameFormControl.errors.required">
{{ 'errors.requiredField' | translate }}
</div>
<div *ngIf="firstNameFormControl.errors.noWhiteSpaceValidator">
{{ 'errors.noWhiteSpace' | translate }}
</div>
</div>
....
</form>
消息 Validator.required 正常显示。尽管如此,然后我删除了 Validator.required , noWhiteSpaceValidator 消息将不会出现。
答案 0 :(得分:0)
下面是我的代码段
public loginForm: FormGroup;
constructor(
private formBuilder: FormBuilder
) {}
get UserName() {
return this.loginForm.get("UserName");
}
ngOnInit() {
this.buildForm();
}
private buildForm() {
this.loginForm = this.formBuilder.group({
UserName: ["", Validators.required, this.noWhitespaceValidator]
});
}
private noWhitespaceValidator(control: FormControl) {
const isWhitespace = (control.value || "").trim().length === 0;
const isValid = !isWhitespace;
return of(isValid ? null : { whitespace: true });
}
然后在我的组件中
<div *ngIf="UserName.errors.whitespace">
you have a whitespace
</div>