我有一个 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/