0
我試圖做一個離子2項目表單驗證,我有使用angular docs方法的問題如下:如何直接使用HTML表單驗證返回值
<div *ngIf="formErrors.spot" >
{{ formErrors.spot }}
</div>
直接顯示由驗證例程返回的消息。
作爲一種變通方法,我用下面所示的方法,但我想擺脫所有這些結構的在HTML
<p *ngIf="signUpForm.controls.spot.hasError('not a whole number')">
This is tooootally not a whole number
</p>
,而使用的角度上面的方法將取代所有這一切,以便我不必維護兩組錯誤消息(在驗證器和html本身中)。
當我嘗試使用角度方法時,它看起來像formErrors是未定義的。
下面的代碼
HTML
<ion-header>
<ion-navbar color="dark">
<ion-title>NEW USER SIGNUP</ion-title>
</ion-navbar>
</ion-header>
<ion-content class="login-content" padding>
<div>
<form [formGroup]="signUpForm">
<ion-list inset>
<ion-item [class.invalid]="!signUpForm.controls.spot.valid && (signUpForm.controls.spot.dirty)">
<ion-input placeholder="Parking Spot Number" formControlName="spot" [(ngModel)]="registerCredentials.spot"></ion-input>
</ion-item>
<div *ngIf="!signUpForm.controls.spot.valid && !signUpForm.controls.spot.pending && (signUpForm.controls.spot.dirty)">
<p *ngIf="signUpForm.controls.spot.hasError('too low')">
Seriously... waaaay too low.
</p>
<p *ngIf="signUpForm.controls.spot.hasError('too high')">
This is waaaay too high
</p>
<p *ngIf="signUpForm.controls.spot.hasError('not a number')">
This is tooootally not a number
</p>
<p *ngIf="signUpForm.controls.spot.hasError('not a whole number')">
This is tooootally not a whole number
</p>
</div>
</ion-list>
</form>
</div>
</ion-content>
下面是相關的TS文件
import { Component, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { SpotValidator } from '../../validators/spotValidator2';
import * as moment from 'moment'
@Component({
selector: 'page-signup',
templateUrl: 'signup.html'
})
export class SignupPage2 {
@ViewChild('signupSlider') signupSlider: any;
signUpForm: FormGroup;
private debugMode: boolean = true;
registerCredentials = {
spot: '',
};
constructor(
public formBuilder: FormBuilder,
) {
this.signUpForm = formBuilder.group({
spot: ['', [SpotValidator.isValid]]
});
}
}
最後,相關的驗證
import { FormControl } from '@angular/forms';
export class SpotValidator {
static isValid(control: FormControl): any {
if(control.value == ""){
return null
}
if(isNaN(control.value)){
return {
"not a number": true
};
}
if(control.value % 1 !== 0){
return {
"not a whole number": true
};
}
if (control.value > 260){
return {
"too high": true
};
}
if (control.value < 31){
return {
"too low": true
};
}
return null;
}
}
總之,我怎麼可以用這樣的:在上面的代碼
<p *ngIf="signUpForm.controls.spot.hasError('not a whole number')">
This is tooootally not a whole number
</p>
:
<div *ngIf="formErrors.spot" >
{{ formErrors.spot }}
</div>
替換這些?