[angular]表单验证

2017-12-29  本文已影响0人  hulaye

html:

<form [formGroup]="myForm" (submit)="saveDataList()">
<ion-item>
<ion-label>工作时长(h)
<span class="text-red">*</span>:
</ion-label>
<ion-input type="text" formControlName="cost" [(ngModel)]="dataList.cost" [readonly]="!isread"></ion-input>
</ion-item>
<div *ngIf="verifyMessages.cost.errorMsg" class="validation-failed">{{verifyMessages.cost.errorMsg}}</div>
<button type="submit" [disabled]="!myForm.valid" ion-button block>保存</button>
</form>
([ngModelOptions]="{standalone: true}"
/*当设置了这个属性,<input>的 FormControl 对象就不会添加到FormGroup内,也就不能通过{{ f.controls['firstField']?.value }}
 索引到该对象的值了。*/

Validators.ts:(表单验证控制)

/**
 * Created by yanxiaojun617@163.com on 3-12.
 */
import {Injectable} from "@angular/core";
import {Validators as angularValidators, AbstractControl} from '@angular/forms';

@Injectable()
export class Validators extends angularValidators {

  /*E-mail*/
  static email = function (control: AbstractControl) {
    return Validators.validatorsByPattern('email', control, '([a-z0-9]*[-_]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[\.][a-z]{2,3}([\.][a-z]{2})?');
  };

  /*手机号码*/
  static phone = function (control: AbstractControl) {
    return Validators.validatorsByPattern('phone', control, '1[0-9]{10,10}');
  };

  /*中文*/
  static chinese = function (control: AbstractControl) {
    return Validators.validatorsByPattern('chinese', control, '[(\u4e00-\u9fa5)]+');
  };

  /*英文、数字包括下划线*/
  static legallyNamed = function (control: AbstractControl) {
    return Validators.validatorsByPattern('legallyNamed', control, '[A-Za-z0-9_]+');
  };

  /*数字*/
  static number = function (control: AbstractControl) {
    return Validators.validatorsByPattern('number', control, '[0-9]+');
  };

  private static validatorsByPattern = function (name: string, control: AbstractControl, pattern: string) {
    let validatorFn = Validators.pattern(pattern)(control);
    if (validatorFn != null) {
      validatorFn[name] = validatorFn['pattern'];
    }
    return validatorFn;
  };
}

.ts(页面逻辑)

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { FormBuilder } from '@angular/forms';
import { Validators } from "../../../../providers/util/Validators";
@IonicPage()
@Component({
    selector: 'page-rs-detail',
    templateUrl: 'rs-detail.html',
})
export class RsDetailPage {
    myForm: any;
    verifyMessages = {
        'cost': {
            'errorMsg': '',
            'required': '工作用时为必填项',
            'number': '请输入正确的数字类型'
        },
        'defectreason': {
            'errorMsg': '',
            'required': '故障原因为必填项'
        }
    };
    constructor(public navCtrl: NavController,
        public navParams: NavParams,
        private formBuilder: FormBuilder) {
            this.myForm = this.formBuilder.group({
                cost: ['', [Validators.required,Validators.number]],
                defectreason: ['', [Validators.required]]
              });
              this.myForm.valueChanges
              .subscribe(data => {
                const verifyMessages = this.verifyMessages;
                for (const field in verifyMessages) {
                  verifyMessages[field].errorMsg = '';
                  const control = this.myForm.get(field);
                  if (control && control.dirty && !control.valid) {
                    const messages = verifyMessages[field];
                    for (const key in control.errors) {
                      messages[key] && (verifyMessages[field].errorMsg += messages[key] + ' ');
                    }
                  }
                }
              });
    }   
}
上一篇下一篇

猜你喜欢

热点阅读