I am trying to validate an input field that should allow only positive numbers greater than zero, and for this I'm using Validators.compose() with some rules. The problem is that I can't validate this field, somehow it isn't working as expected. Am I doing something wrong? How could I fix it? Thanks
TypeScript code:
export class SignupPage {
public signup: FormGroup;
constructor(public navCtrl: NavController, public navParams: NavParams, public formBuilder: FormBuilder) {
// setting up sign up form
this.signup = formBuilder.group({
"name": ["", Validators.required],
"age": ["", Validators.compose([Validators.required, Validators.pattern('^[1-9]\d*$')])],
"city": ["", Validators.required]
})
}
onSubnmit(form) {
console.log(form);
let user = {
'name': form.name,
'age': form.age,
'city': form.city
}
}
HTML Code:
<form [formGroup]="signup" (ngSubmit)="onSubmit(this.signup.value)">
<ion-list class="signup-input">
<ion-item>
<ion-label floating>What is your name?</ion-label>
<ion-input type="text" formControlName="name" [class.invalid]="!signup.valid && (signup.controls.name.dirty || submitAttempt)"></ion-input>
</ion-item>
<ion-item *ngIf="!signup.controls.name.valid && (signup.controls.name.dirty || submitAttempt)" >
<small>Please fill out this field.</small>
</ion-item>
<ion-item>
<ion-label floating>How old are you?</ion-label>
<ion-input type="text" formControlNale="age" [class.invalid]="!signup.controls.age.valid && (signup.controls.age.dirty || submitAttempt)"></ion-input>
</ion-item>
<ion-item *ngIf="!signup.controls.age.valid && (signup.controls.age.dirty || submitAttempt)" >
<small>Please enter a valid age.</small>
</ion-item>
<ion-item>
<ion-label floating>What is your city?</ion-label>
<ion-input type="text" formControlName="city" [class.invalid]="!signup.controls.city.valid && (signup.controls.city.dirty || submitAttempt)"></ion-input>
</ion-item>
<ion-item *ngIf="!signup.controls.city.valid && (signup.controls.city.dirty || submitAttempt)" >
<small>Please fill out this field.</small>
</ion-item>
</ion-list>
<ion-grid>
<ion-row>
<div class="signup-btn">
<button ion-button block width-90 type="submit" [disabled]="!this.signup.valid">Get in</button>
</div>
</ion-row>
</ion-grid>
</form>
And this is how it looks like:
