Ionic2使用FormBuilder和Validators进行表单验证

ionic2中的form表单是验证方式是基于angular2的form验证,在angular2的form经过更新后,从以前的

import { FormBuilder, Control, ControlGroup, Validators, FORM_DIRECTIVES } from '@angular/common';

更新成了从forms中引入

import { FormBuilder, Validators, FormGroup } from '@angular/forms';
变化后 变化前
formGroup ngFormModel
formControl ngFormControl
formControlName ngControl
formGroupName ngControlGroup
formArrayName ngControlGroup
FormControl() Control
FormGroup() ControlGroup
FormArray() ControlArray

并且之前form使用的名字也存在一些变化

变化后 变化前
formGroup ngFormModel
formControl ngFormControl
formControlName ngControl
formGroupName ngControlGroup
formArrayName ngControlGroup
FormControl() Control
FormGroup() ControlGroup
FormArray() ControlArray

具体变化可以参看详情

以下为最新的使用FormBuilder进行表单验证的代码

----login.ts-----

import { TabsPage } from './../tabs/tabs';
import { StorageService } from './../../providers/storage-service';//这里引入了一个自己创建的服务,主要用于存储用户信息
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { FormBuilder, Validators, FormGroup } from '@angular/forms';


@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
  providers: [StorageService]
})
export class LoginPage {

  loginForm: FormGroup;
  username: any;
  password: any;
  constructor(public navCtrl: NavController, private formBuilder: FormBuilder, public storage: StorageService) {
    this.loginForm = formBuilder.group({
      username: ['', Validators.compose([Validators.minLength(11), Validators.maxLength(11), Validators.required, Validators.pattern("^(13[0-9]|15[012356789]|17[03678]|18[0-9]|14[57])[0-9]{8}$")])],
      password: ['', Validators.compose([Validators.required, Validators.minLength(6)])]
    })
    this.username = this.loginForm.controls['username'];
    this.password = this.loginForm.controls['password'];
  }


  login(value) {
    if (value.username == "手机号码" && value.password == 123456) {
      this.storage.setUser(value);
      this.navCtrl.push(TabsPage);
    } else {
      console.log("登录失败");
    }

  }

}

----login.html----


    
        用户登录
    



    
用户名:
* 请输入用户名
* 请输入正确的电话号码
密 码:
* 请输入密码
* 密码长度最少为六位

你可能感兴趣的:(Ionic2使用FormBuilder和Validators进行表单验证)