我有一个简单的输入是为了一个电话号码,我想验证,只有数字和长度是10位数字。Angular 2:简单的输入验证
<input [(ngModel)]="client.phone" class="form-input" name="phone" type="phone" [value]="client.phone">
我能做些什么来验证这一点没有使用FormBuilder
?似乎FormBuilder
只是使事情复杂化,我只想验证这一个输入。
我有一个简单的输入是为了一个电话号码,我想验证,只有数字和长度是10位数字。Angular 2:简单的输入验证
<input [(ngModel)]="client.phone" class="form-input" name="phone" type="phone" [value]="client.phone">
我能做些什么来验证这一点没有使用FormBuilder
?似乎FormBuilder
只是使事情复杂化,我只想验证这一个输入。
<input type="number" name="phone" max="10">
可以使用型号和最大
这不会将数字限制在1到10之间吗?我认为OP需要1到10位数字。 – DeborahK
^这是正确的 –
这里是我的Pluralsight课程的例子。这第一个例子是使用模板驱动的表单。它使用一个简单的模式来验证电子邮件地址:
<div class="form-group"
[ngClass]="{'has-error': (emailVar.touched || emailVar.dirty) && !emailVar.valid }">
<label class="col-md-2 control-label"
for="emailId">Email</label>
<div class="col-md-8">
<input class="form-control"
id="emailId"
type="email"
placeholder="Email (required)"
required
pattern="[a-zA-Z0-9._%+-][email protected][a-zA-Z0-9.-]+"
[(ngModel)]="customer.email"
name="email"
#emailVar="ngModel" />
<span class="help-block" *ngIf="(emailVar.touched || emailVar.dirty) && emailVar.errors">
<span *ngIf="emailVar.errors.required">
Please enter your email address.
</span>
<span *ngIf="emailVar.errors.pattern">
Please enter a valid email address.
</span>
<!-- This one does not work -->
<span *ngIf="emailVar.errors.email">
Please enter a valid email address.
</span>
</span>
</div>
</div>
本示例对同一事物使用Reactive Forms。
this.customerForm = this.fb.group({
firstName: ['', [Validators.required, Validators.minLength(3)]],
lastName: ['', [Validators.required, Validators.maxLength(50)]],
email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-][email protected][a-z0-9.-]+')]],
sendCatalog: true
});
所以使用一个模式是非常多的角度技术。我只是把你指向HTML网站,因为它提供了一些关于电话号码模式的建议,你可以从中选择和使用这些模式来代替我的示例中显示的电子邮件模式。
让我知道如果你想链接到关联的github代码。
https://angular.io/docs/ts/latest/guide/forms.html
<form role="form" #f="ngForm" novalidate>
<input class="form-input" type="number" [(ngModel)]="client.phone" name="phone" max="10">
<button type="submit" [disabled]="f.form.invalid">
</form>
通过内置的模式验证这是很容易:
<input [(ngModel)]="client.phone" pattern="[0-9]{10}" class="form-input" name="phone" type="phone" [value]="client.phone">
你是否还在寻找留在模板驱动的形式? – Winnemucca
这似乎更简单,我是Angular2的新手 –
我正在寻找接近此角度的方法 –