代码之家  ›  专栏  ›  技术社区  ›  anhtv13

角度6验证数字输入

  •  2
  • anhtv13  · 技术社区  · 7 年前

    我有一个输入,类型是数字。如果输入超出此范围,我要设置最小值和最大值(<最小值或大于;最大),将显示错误。

    我的问题是,如果输入不是空的,而是无效的,错误就会消失(例如:min=10,max=20,input=2000,仍然不显示错误)。

    我在这个网站上搜索,有一个关于验证的帖子,但解决方法是使用<md输入容器>和<md错误>。我不想使用<md输入容器>和<md错误>。

    参考文献: here

    有什么办法解决我的问题吗?

    我的add-hero.component.html:

    <div class="publishedYear">
    <label>Publish Year: </label>
    <input type="number" id="PublishedYear" name="PublishedYear" required min="10" max="20" 
    [(ngModel)]="hero.PublishedYear" #publishedYear="ngModel">
    <p class="alert alert-danger invalid" *ngIf="publishedYear.errors">Invalid Published Year</p>
    </div>
    

    我的英雄.ts

    export class Hero {
    Id: number;
    Name: string;
    PublishedYear: number;
    Complete?: boolean;
    }
    
    3 回复  |  直到 7 年前
        1
  •  15
  •   CodeChanger    6 年前

    当您使用输入时 type="number"

    为此,有两种解决方案

    1) 使用角度窗体验证将窗体控件添加到输入中在线将有几个示例

    2) 更改文本框或单击按钮时调用函数,以验证用户输入的数字是否与ts文件中的表达式匹配。

    使用表单验证

    myForm = new FormGroup({}) // Instantiating our form
    
    constructor(private fb: FormBuilder){ // Injecting the ReactiveForms FormBuilder.
      this.myForm = fb.group({
        // Adding the "myNum" input to our FormGroup along with its min-max Validators.
        'myNum': ['', [Validators.min(5), Validators.max(10)]] 
      })
    }
    

    在HTML中

    <form [formGroup]="myForm"> <!-- Binding myForm to the form in the template -->
        <label for="myNum">Some Val</label>
        <!-- formControlName binds our myNum field declared in the ts code. -->
        <input type='number' id="myNum" formControlName="myNum">
        <div *ngIf="myForm.controls['myNum'].hasError('max')">
              Minimum required number is 15.
        </div> 
    </form>
    
        2
  •  9
  •   Tibin Thomas    7 年前

    See the sample code in stackblitz

    import { Component } from '@angular/core';
    
    import { Directive, Input, forwardRef } from "@angular/core";
    import {
        Validator, AbstractControl, NG_VALIDATORS, Validators, ValidatorFn
        } from "@angular/forms";
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      hero: any = {};
    }
    
    
    @Directive({
        selector: "[min][formControlName],[min][formControl],[min][ngModel]",
        providers: [
            { provide: NG_VALIDATORS,
                useExisting: forwardRef(() => MinDirective),
                multi: true }
        ]
    })
    export class MinDirective implements Validator {
        private _validator: ValidatorFn;
        @Input() public set min(value: string) {
            this._validator = Validators.min(parseInt(value, 10));
        }
    
        public validate(control: AbstractControl): { [key: string]: any } {
            return this._validator(control);
        }
    }
    
    @Directive({
        selector: "[max][formControlName],[max][formControl],[max][ngModel]",
        providers: [
            { provide: NG_VALIDATORS,
                useExisting: forwardRef(() => MaxDirective),
                multi: true }
        ]
    })
    export class MaxDirective implements Validator {
        private _validator: ValidatorFn;
        @Input() public set max(value: string) {
            this._validator = Validators.max(parseInt(value, 10));
        }
    
        public validate(control: AbstractControl): { [key: string]: any } {
            return this._validator(control);
        }
    }
    
    <input type="number" [(ngModel)]="hero.count" name="count" #count="ngModel" required min="1" max="100">
    
    <p *ngIf="count.invalid">Invalid Published Year</p>
    

        3
  •  4
  •   anhtv13    7 年前

    经过几个小时的研究,我终于得到了答案: page

    如果你有任何像我一样的问题,这里是答案。

    我的.html文件:

    <form [formGroup]="myForm">
    <label for="publishedYear">Publish Year: </label>
    <input type="number" id="PublishedYear" formControlName="publishedYear">
    <div *ngIf="f.publishedYear.errors">
      Invalid Published Year
    </div>
    

    我的.ts文件:

    import { Component, OnInit, Input } from '@angular/core';
    import { Hero } from '../Hero';
    import { HeroService } from '../hero.service';
    import { Router } from '@angular/router';
    import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from 
    '@angular/forms';
    
    @Component({
    selector: 'app-hero-add',
    templateUrl: './hero-add.component.html',
    styleUrls: ['./hero-add.component.css']
    })
    export class HeroAddComponent implements OnInit {
    
    hero: Hero = new Hero();
    
    myForm = new FormGroup({}) // Instantiating our form
    
    get f() { return this.myForm.controls; }
    
    constructor(private heroService: HeroService, private router: Router, private 
    formBuilder: FormBuilder) {
        this.myForm = formBuilder.group({     
        publishedYear: ['', [Validators.min(1990), Validators.max(2018)]]
    });
    }
    
      ngOnInit() {
      }     
    }
    
        4
  •  1
  •   safeena rasak    5 年前

    <input type="text" class="form-control" (input)="onSearchChange($event.target.value)">
    
    onSearchChange(searchValue: string): void {  
      console.log(searchValue);
    // validate the value here
    }
    
        5
  •  1
  •   Ch Asjad Mahmood    5 年前

    在模板驱动的表单中处理min-max验证的最简单的方法是使用html的pattern属性,并为其分配一个regex数,例如输入的范围为0-24

    <input pattern="([0-9]|1[0-9]|2[0-4])" required type="number" id="monday" name="monday" [(ngModel)]="pullingStrategy.one" #monday="ngModel" />
    

    如果您想为任何其他范围生成正则表达式编号,请使用 链接 https://3widgets.com/

    推荐文章