Angular2 Javascript 验证 输入数字而不是字符

Angular2 Javascript Validating Input number not character

本文关键字:字符 数字 Javascript 验证 输入 Angular2      更新时间:2023-09-26

链接到完整项目(不带nodes_modules)https://www.dropbox.com/s/4qd8x97ih1f1nho/workinghw4zipped%20%281%29.zip?dl=0

注意:运行它后,有关此问题的所有内容都在网站的"全部编辑"部分中,单击该部分以访问该表

网站这一部分的目的是让用户为表中的每一行输入名称和价格。

如果用户在价格框中输入字符(而不是数字),则必须在某处显示"无效输入"消息,该消息会在用户键入时自行更新。

我应该在代码中添加或更改什么,以允许用户在价格框中输入字符(而不是数字)时显示"无效输入"消息?

该 html 文件:

<h1>{{title}}</h1>
<h2>My Heroes</h2>
<form [ngFormModel]="myForm" class="ui form">
<table *ngFor="#hero of heroes">
  <thead>
    <tr>
      <th> ID </th>
      <th> Hero Name</th>
      <th> Price </th>
    </tr>
  </thead>
  <tbody>
    <tr>
        <td id="id"><label>{{hero.id}}</label></td>
        <td id="name"><input type = "String" [(ngModel)]="hero.name" placeholder="Pristine name" /></td>
        <div class="field">
        <td id="price">
          <input type = "number" 
          [(ngModel)]="hero.price"
           placeholder="Pristine Price" 
          [ngFormControl]="myForm.find('price')"
          />Input Pristine</td>
           </div>

   <div *ngIf="!sku.control.valid"  
         class="ui error message ">Price can only be an integer.</div>  
       <div *ngIf="sku.control.hasError()"  
         class="ui error message">Input is invalid</div>  
    <div *ngIf="!myForm.valid"  
      class="ui error message">Not pristine.</div>
</tr>
</tbody>
</table>
</form>

.ts 文件:

import {Component, OnInit} from 'angular2/core';
import {
  FORM_DIRECTIVES,
  FormBuilder,
  Control, ControlGroup,
  Validators
} from 'angular2/common';
import {Router} from 'angular2/router';
import {Hero} from './hero';
import {HeroService} from './hero.service';

@Component({
  selector: 'SpreadSheetComponent',
  templateUrl: 'app/spreadsheeteditall.component.html',
  styleUrls: ['app/spreadsheeteditall.component.css'],
  providers: [HeroService],
})

export class SpreadSheetComponent {
  myForm: ControlGroup;
  price;
  onSubmit(value: string): void {
    console.log('you submitted value: ', value);
  }  
  heroes: Hero[];
  selectedHero: Hero;
  constructor(fb: FormBuilder, private _heroService: HeroService, private _router: Router) { 
        function skuValidator(control: Control) : { [s: string]: boolean } {
      if (!control.value.match(/[0-9][0-9]*('.[0-9][0-9])?$/)) {
        return { invalidSku: true };
      }
    };
    this.myForm = fb.group({
      'sku': ['', Validators.compose([
        Validators.required, skuValidator])]
    });
 this.price = this.myForm.controls['sku'];
  }
  getHeroes() {
    this._heroService.getHeroes().then(heroes => this.heroes = heroes);
  }
  gotoDetail() {
    this._router.navigate(['HeroDetail', { id: this.selectedHero.id }]);
  }
  ngOnInit() {
    this.getHeroes();
  }
  onSelect(hero: Hero) { this.selectedHero = hero; }
}

我不确定这是否有效。但这是我解决你的问题的方法。我希望它对你有用。

将价格的输入控制替换为此 -

<input type = "number" 
      [(ngModel)]="hero.price"
       placeholder="Pristine Price" 
      [ngFormControl]="myForm.find('price')"
      (keypress)="showErrorIfNotANumber($event)"
      />

然后添加此标签以在您想要的任何位置显示消息 -

<p style="color:red;" *ngIf="errorMessage">{{errorMessage}}</p>

修改您的 component.ts 文件 -

1) 添加一个变量 -

public errorMessage:any = null;

2) 添加此功能 -

public showErrorIfNotANumber(event:any){
if(event.charCode>=48 && event.charCode<=57){
    this.errorMessage = null;
}
else{
    this.errorMessage = 'you can only enter numbers here!';
}
}

您可以通过在角度 2 中使用 isNaN 函数找到 isNumber。

  checkData(username: string, email: string, phone: string, msg: string) {
    if (isNaN(Number(phone))) {
        //code
    } else {
    }
  }
相关文章: