通过最小长度、最大长度、电子邮件、所需号码等验证表格.角度2

Validating forms by minlenght, maxlenght, email, number, required etc.. angular 2

本文关键字:验证 表格 号码 角度 电子邮件      更新时间:2023-09-26

我在角度中有一个样本形式

app.html

<form [ngFormModel]="newListingForm" (ngSubmit)="submitListing(newListingForm.value)">
<input type="radio" #typeRadio="ngForm" [ngFormControl]="newListingForm.controls['typeRadio']" value="Event" id="type-event_radio" required>
<input type="radio" #typeRadio="ngForm" [ngFormControl]="newListingForm.controls['typeRadio']" value="Venue" id="type-venue_radio" required>
<input type="text" placeholder="New Title" #mainTitleInput="ngForm" [ngFormControl]="newListingForm.controls['mainTitleInput']" id="main-title_input" class="transparent">
<input type="email" #emailAddressInput="ngForm" [ngFormControl]="newListingForm.controls['emailAddressInput']" id="email-address_input" required>
<!-- etc -->
</form>

app.ts

import {Component} from 'angular2/core';
import {FORM_DIRECTIVES, FormBuilder, ControlGroup, Validators} from 'angular2/common';
@Component({
  templateUrl : 'app/components/new-listing/app.html',
  directives: [FORM_DIRECTIVES]
})
export class NewListingComponent {
  //Helpers
  newListingForm: ControlGroup;
  //Costructor
  constructor(
    fb: FormBuilder
  ){
    //New Listing Form
    this.newListingForm = fb.group({
      'typeRadio': ['', Validators.required],
      'mainTitleInput': ['', Validators.required],
      'emailAddressInput': ['', Validators.required],
    });
  }
  //TODO Form submission
  submitListing(value: string): void {
    console.log("Form Submited");
  }
}

目前,我看到的唯一验证是谷歌在必填字段上提供的默认验证。一切都过去了。我一直在研究文档,最小/最大长度似乎很容易用我当前的设置来实现,但还有另一个有趣的asp NG_VALIDATORS,我认为(不确定)它通过查看表单中的type="email"required等来提供验证。本质上,我希望能够通过angular2显示invalid emailthis field is required等消息。

只需使用这样的表达式(Bootstrap示例)来利用与输入相关联的控件的属性(有效与否、错误等):

<form [ngFormModel]="newListingForm">
  <!-- Field name -->
  <div class="form-group form-group-sm"
       [ngClass]="{'has-error':!newListingForm.controls.mainTitleInput.valid}">
    <label for="for"
       class="col-sm-3 control-label">Name:</label>
    <div class="col-sm-8">
      <input [ngFormControl]="newListingForm.controls.mainTitleInput"
             [(ngModel)]="newListing.mainTitleInput"/>
      <span *ngIf="!newListingForm.controls.mainTitleInput.valid"
            class="help-block text-danger">
        <span *ngIf="newListingForm.controls.errors?.required">
          The field is required
        </span>
      </span>
    </div>
  </div>
</form>

使用此示例,包含错误的字段将显示为红色,并动态显示错误消息。

此外,您还为字段添加了实现自定义验证器:

export class CityValidator {
  static validate(control: Control) {
    var validValues = [ 'mycity', ... ];
    var cnt = validValues
      .filter(item => item == control.value)
      .length; 
    return (cnt == 0) ? { city: true } : null;
  }
}

只需将其添加到字段的验证器中:

this.newListingForm = fb.group({
  'myfield': ['', Validators.compose([
     Validators.required, CityValidator.validate])]
  (...)
});

希望它能帮助你,Thierry

@Ilja您正处于良好的轨道上,使用以下代码改进您的代码:

this.newListingForm = fb.group({
  'typeRadio': ['',  Validators.compose([Validators.required, Validators.minLength(2), Validators.maxLength(40)])],
  'mainTitleInput': ['', Validators.compose([Validators.required, Validators.minLength(2), Validators.maxLength(40)])],
  'emailAddressInput': ['', Validators.compose([Validators.required, Validators.minLength(2), Validators.maxLength(40)])],
});

考虑这个例子(使用自定义电子邮件验证器)https://plnkr.co/edit/5yO4HviXD7xIgMQQ8WKs?p=info