简体   繁体   中英

Form validation is not working with Angular 2 FormBuilder in Ionic 2

I am building a Ionic 2 (typescript) application. Having problem ONLY in a simple model-driven form validation in checkbox ( ion-checkbox tag).

I'm using FormBuilder to build the form module. I want the form to be validated / not validated based on the checked state of a checkbox input control. But its working one-way only. Here's my code :

reg.html

<ion-content padding>
    <form class="client_profile" [formGroup]="regForm">
        <div class="profile_pic" id="profile_pix">
            <img src="build/images/home.svg" id="client_camera_pic" />
        </div>
        <ion-item>
            <ion-label floating>What we would call you?</ion-label>
            <ion-input type="text" formControlName="client_name"></ion-input>
        </ion-item>
        <ion-item>
            <ion-label floating>Choose your username</ion-label>
            <ion-input type="text" name="client_username" value="" #client_username formControlName="client_username"></ion-input>
        </ion-item>
        <ion-item>
            <ion-label floating>Where we will drop your Email?</ion-label>
            <ion-input type="email" name="client_email" value="" #client_email formControlName="client_email"></ion-input>
        </ion-item>
        <ion-item>
            <ion-label floating>We also need your phone number</ion-label>
            <ion-input type="number" name="client_phone" value="" #client_phone formControlName="client_phone"></ion-input>
        </ion-item>
        <ion-item class="reg_terms">
            <ion-checkbox secondary #terms name="terms" value="" checked="false" formControlName="terms"></ion-checkbox>
            <ion-label>I accept the <a href="#">Terms & Conditions</a></ion-label>
        </ion-item>
    </form>
    <div>
        <ion-buttons right class="client_reg_done">
            <button danger class="reg_complete" (click)="process_client_reg()" [disabled]="!regForm.valid">NEXT</button>
        </ion-buttons>
    </div>
</ion-content>

reg.ts

import { Component, ViewChild, ElementRef } from '@angular/core';
import { FORM_PROVIDERS, FormBuilder, FormControl, FormGroup, AbstractControl, Validators, REACTIVE_FORM_DIRECTIVES } from '@angular/forms';
import { App, NavController, ViewController, ModalController, LoadingController, LoadingOptions } from 'ionic-angular';

@Component({
    templateUrl: "build/pages/registration/reg.html"
})
export class Registration {
    ngAfterViewInit(){

    }

    regForm: FormGroup;

    constructor(public app: App, public nav: NavController, public viewCtrl: ViewController, public elem: ElementRef, public modalCtrl: ModalController, public loading: LoadingController, public fb: FormBuilder){

    }

    ngOnInit() {
        this.regForm = this.fb.group({
            client_name: ['', Validators.compose([Validators.required, Validators.maxLength(30), Validators.pattern('^[a-zA-Z\. ]+$')])],
            client_username: ['', Validators.compose([Validators.required, Validators.maxLength(20), Validators.pattern('[a-zA-Z0-9-_\.]+')])],
            client_email: ['', Validators.compose([Validators.required, Validators.pattern('^[a-zA-Z0-9-_]+@[a-zA-Z]+\.[a-zA-Z]{2,4}$')])],
            client_phone: ['', Validators.compose([Validators.required, Validators.pattern('^[\+0-9]{10,12}$')])],
            terms: [null, Validators.required]      
        });
    }
}

Actual view:

regview

Checking / unchecking the Terms & Condition checkbox doesn't updating the validation logic and the 'NEXT' button disabled state is not updating. Its because form validation isn't taking account this checkbox. Some help is appreciated.

Initialising your terms control with null seems to break the emission of change events. Try adding this subscription:

this.regForm.valueChanges.subscribe(v => {
  console.log('Required validation failed: ' + this.form.controls['terms'].hasError('required'));
  console.log('Required validation touched: ' + this.form.controls['terms'].touched);
  console.log('Required validation status: ' + this.form.controls['terms'].status);
});

Toggling the terms checkbox doesn't result in any logging. This might be a bug.

Now change your control to be initialised as false and try again: terms: [false, Validators.required] This time the logging happens and you can see what's going on.

Unfortunately, now the control is in the valid state as soon as it loads. You can check that with similar logging after building your FormGroup. The best solution would be to create an is-true custom validator, but a quick and dirty solution would be to change your button:

[disabled]="!regForm.valid || !form.controls.terms.touched"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM