javascript - 按最小长度、最大长度、电子邮件、数字、必需等方式验证表格。angular 2

标签 javascript angular forms validation

我有一个 Angular 示例表单

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 email this 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;
  }
}

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

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

希望对你有帮助, 蒂埃里

关于javascript - 按最小长度、最大长度、电子邮件、数字、必需等方式验证表格。angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34789250/

相关文章:

javascript - 禁止编辑内嵌文本

javascript - $.getJSON() 在 IE9 中有效,但在 Chrome 和 FireFox 中无效,我的代码有什么问题?

php - 使用表单按钮提交 GET 值

javascript - 表单发布参数以 URL 结尾

javascript - 如何从脚本提交表单

javascript - Azure 媒体播放器 - 版本 2.0 - 设置时未选择选项和设置

Javascript循环第一次运行时有效,但第二次运行时给出NaN,没有逻辑

android - 在 Android 手机上不调用带有 onkeypress 的 Angular 指令

angular - 显示跨字段自定义验证错误消息

angular - 具有条件 <optgroup> 的动态 <select><option> 作为 ng-container 不工作