我正在尝试仅使用字母验证用户字段。
遵循https://angular.io/api/forms/Validators#pattern
上的文档
我没有得到预期的结果。
Validator。必需的作品。 Validator.minLength有效。 但是模式却没有。
我需要用户字段中只有字母。 已经在论坛上查找了类似的问题,并尝试了一些实现方式,但无法正常工作。
我还尝试将直接添加到html标签[pattern]='onlyLetters'
中,但也没有成功。
html
<form (ngSubmit)="onSubmitNewUser()" [formGroup]="userFormGroup" >
<mat-card>
<mat-card-title fxLayoutAlign="center">{{'USERS.NEW'|translate}}</mat-card-title>
<mat-card-content fxLayoutAlign="left" fxLayout="column">
<mat-form-field fxFlex="100%">
<mat-label>{{'USERS.GROUP'|translate}}</mat-label>
<mat-select formControlName="group" >
<mat-option *ngFor="let group of groups" value="{{ group.users_group_id }}">{{ group.users_group_name }}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field fxFlex="100%">
<input
[pattern]="pattern"
placeholder="{{'USERS.USERNAME'|translate}}"
type="text"
formControlName="username"
matInput />
<mat-error *ngIf="formControlUsername.hasError('required')" >
{{'VALIDATION.REQUIRED'|translate}}
</mat-error>
</mat-form-field>
<mat-form-field fxFlex="250px" hintLabel="{{'VALIDATION.PASSWORD_HINT'|translate}}">
<input
type="password"
placeholder="{{'USERS.PASSWORD'|translate}}"
matInput
formControlName="password"/>
<mat-hint align="end"> {{ formControlPassword.value?.length }} / 6 </mat-hint>
<mat-error>{{'VALIDATION.MIN_LENGTH'|translate}}</mat-error>
</mat-form-field>
</mat-card-content>
<mat-card-actions fxLayoutAlign="left">
<button
type="submit"
color="primary"
mat-raised-button
[disabled]="userFormGroup.invalid">{{'SAVE'|translate}}</button>
</mat-card-actions>
</mat-card>
</form>
TS文件
import { Component, OnInit} from '@angular/core';
import { FormControl, FormGroup, Validators} from '@angular/forms';
import { GroupsModel} from '../_models/groups.model';
import { UsersService} from '../_services/users.service';
@Component({
selector: 'app-users-add',
templateUrl: './users-add.component.html',
styleUrls: ['./users-add.component.scss']
})
export class UsersAddComponent implements OnInit {
pattern = "[a-zA-Z]*";
formControlGroup = new FormControl('',{
validators: [Validators.required]
});
formControlUsername = new FormControl('',{
validators: [
Validators.required,
Validators.pattern(this.pattern)
]
});
formControlPassword = new FormControl('',{
validators: [
Validators.required,
Validators.minLength(6)
]
});
userFormGroup: FormGroup;
groups: GroupsModel[] = [];
constructor(private usersService: UsersService) { }
ngOnInit() {
this.userFormGroup = new FormGroup({
group: this.formControlGroup,
username: this.formControlUsername,
password: this.formControlPassword
});
this.usersService.getGroups().subscribe( data => {
this.groups = data
});
}
onSubmitNewUser() {
console.log(this.userFormGroup.value);
}
}