限制用户使用ngModel输入最大5位整数,最大2位小数,角度2

时间:2018-02-12 18:18:43

标签: javascript angular

我有一个输入文本字段,其中包含[(ngModel)],我的要求是允许用户只输入最多2位小数的最大5位数字。创建指令是最佳解决方案,但我不知道如何带这个功能。请帮忙。

要求是 - 99999.99是正确的                         99.9也是正确的。

我使用数字管[ngModel] ="费用|数字:' 1.0-2'但它不起作用..

2 个答案:

答案 0 :(得分:1)

您可以使用<input>的模式属性来验证您的输入。我为你提出的问题添加了一个模式,正/负,0到5位,0到2位小数:

<input name="something" pattern="^[-+]?\d{0,5}(\.\d{0,2})?$">

答案 1 :(得分:0)

您可以通过两种方式实现此目的。模板驱动表单和Reactive表单。请找到下面的示例,它可以了解验证的工作原理。

在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');
    }
  }
}

希望有所帮助