【发布时间】:2018-02-12 18:18:42
【问题描述】:
我有一个包含 [(ngModel)] 的输入文本字段,我的要求是只允许用户输入最多 5 位数字,最多 2 位小数。创建指令是最好的解决方案,但我不知道如何带来这个功能。请帮忙。
要求是 - 99999.99 是正确的 99.9 也是正确的。
我使用了数字管道 [ngModel]="cost |number:'1.0-2' 但它不起作用..
【问题讨论】:
标签: javascript angular
我有一个包含 [(ngModel)] 的输入文本字段,我的要求是只允许用户输入最多 5 位数字,最多 2 位小数。创建指令是最好的解决方案,但我不知道如何带来这个功能。请帮忙。
要求是 - 99999.99 是正确的 99.9 也是正确的。
我使用了数字管道 [ngModel]="cost |number:'1.0-2' 但它不起作用..
【问题讨论】:
标签: javascript angular
您可以使用<input> 的模式属性来验证您的输入。我为您的要求添加了一个模式,正/负,0 到 5 位,0 到 2 位小数:
<input name="something" pattern="^[-+]?\d{0,5}(\.\d{0,2})?$">
【讨论】:
您可以通过两种方式实现这一点。模板驱动的表单和响应式表单。请找到下面的例子,它给出了一些关于验证如何工作的想法。
在 TS 文件中:(模板驱动表单)
import { Component } from '@angular/core';
@Component({
selector: 'sandboxngforms',
template: `
<h1>Hello World</h1>
<!-- by default html5 has validation. if u add a directive called "novalidate" in form tag
then we can build our customised template.
create an id called f so that we can easily group-->
<!--group the form by value id #f instead of submit> use ngSubmit so that u can use the values used in the form and call the function -->
<form novalidate #f="ngForm" (ngSubmit)="onSubmit(f)">
<div class="form-group">
<label>Name</label>
<input
type="text"
class="form-control"
[(ngModel)]="user.name"
name="name"
#userName="ngModel"
minlength="2"
required>
<!-- using the name input field #tagid (i.e userName) write the below if condition
touched is a special directive that allows u when u click on the field and click outside
will produce error-->
<div *ngIf="userName.errors?.required && userName.touched" class="alert alert-danger">Name is required</div>
<div *ngIf="userName.errors?.minlength && userName.touched"
class="alert alert-danger">Name should be at least 2 characters
</div>
</div>
<div class="form-group">
<label>Email</label>
<input
type="text"
class="form-control"
[(ngModel)]="user.email"
name="email"
#userEmail="ngModel"
required
>
<div *ngIf="userEmail.errors?.required && userEmail.touched" class="alert alert-danger">Email is required</div>
</div>
<div class="form-group">
<label>Phone</label>
<input
type="text"
class="form-control"
[(ngModel)]="user.phone"
name="phone"
#userPhone="ngModel"
minlength="10"
>
<div *ngIf="userPhone.errors?.minlength && userPhone.touched" class="alert alert-danger">Enter a valid phone
number
</div>
</div>
<input type="submit" class="btn btn-success" value="Submit">
</form>
`
})
export class SandboxngformsComponent {
// create an user object
user = {
name: '',
email: '',
phone: ''
}
onSubmit({value, valid}) {
if (valid) {
console.log(value);
} else {
console.log('Form is invalid');
}
}
}
希望对你有帮助
【讨论】: