ionic2.0關於表單的驗證

一、html文件,實現提示語說明和提交事件html

<form [ngFormModel]="commissionForm" (ngSubmit)="onSubmit(commissionForm.value)">
<ion-item [class.error]="!offerName.valid && offerName.touched">
                <ion-label class="form-label">標題</ion-label>
                <ion-input item-right [ngFormControl]="offerName" type="text" placeholder="請輸入標題"></ion-input>
            </ion-item>
            <div *ngIf="offerName.hasError('required')&& offerName.touched" class="error-box">* 標題不可爲空!</div>
            <div *ngIf="offerName.hasError('minlength')&& offerName.touched" class="error-box">* 標題最小長度2個字符!</div>
            <div *ngIf="offerName.hasError('maxlength')&& offerName.touched" class="error-box">* 標題最大長度255個字符!</div>

二、ts文件,實現表單約束ide

import {FORM_DIRECTIVES, FormBuilder, Validators, Control, ControlGroup,AbstractControl} from '@angular/common';
@Page({
    templateUrl: 'build/pages/publish/createCommission.html',
    providers: [FormBuilder,CommissionService,ShopService,AppConfig],
    directives: [FORM_DIRECTIVES]
})
 commissionForm:ControlGroup;
    private offerName: AbstractControl;
    constructor(public nav:NavController,private params:NavParams, private fb: FormBuilder,private commissionService:CommissionService,private shopService:ShopService) {
        this.commissionForm = this.fb.group({
            'offerName': ['', Validators.compose([Validators.required, Validators.minLength(2),Validators.maxLength(255)])],
            'residence': new ControlGroup({residenceId: new Control(CustomerSession.getResidenceId())}),
        });
        this.offerName = this.commissionForm.controls['offerName'];
    }

onSubmit(value:string):void {
        this.commissionForm.value.providerType = this.isShop?'MERCHANT':'PERSONAL';
        
        if (this.commissionForm.valid) {
            this.commissionService.addCommission(value).subscribe(
                data => {});
                
                }
}
相關文章
相關標籤/搜索