1. 直接通过html标签验证
<form id=formId #refForm="ngForm">
<div class="col-sm-9">
<input type="text" name="caigouweight" [(ngModel)]="det['caigouweight']" class="form-control" required pattern="^([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(.[0-9]{1,3})?$"/>
<span *ngIf="refForm.controls['caigouweight']?.errors?.pattern && refForm.controls['caigouweight']?.dirty || refForm.controls['caigouweight']?.touched" class="text-danger">请填写xxx</span>
<span *ngIf="refForm.controls['caigouweight']?.errors?.required && refForm.controls['caigouweight']?.dirty || refForm.controls['caigouweight']?.touched" class="text-danger">请填写xxx字段</span>
</div>
<button type="submit" [disabled]="!refForm.form.valid"></button>
</form>
2.使用ts验证
<form [formGroup]="form" class="form-validate mb-lg" role="form" name="form" novalidate="">
<div class="col-sm-9">
<input type="text" formControlName="caigouweight" [(ngModel)]="det['caigouweight']" class="form-control"/>
<span *ngIf="form.controls['caigouweight'].hasError('required') && (form.controls['caigouweight'].dirty || form.controls['caigouweight'].touched)"
class="text-danger">请填写采购量</span>
<span *ngIf="form.controls['caigouweight'].hasError('pattern') && (form.controls['caigouweight'].dirty || form.controls['caigouweight'].touched)"
class="text-danger">请填写正确的格式</span>
</div>
</form>
ts来实现
form:FormGroup;
this.form = fb.group({
'caigouweight': [null, Validators.compose([Validators.required, Validators.pattern('^([0-9]+|[0-9]{1,3}(,[0-9]{3})*)(.[0-9]{1,3})?$')])]
})
网友评论