繁体   English   中英

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

[英]Angular2 Javascript Validating Input number not character

链接到完整项目(没有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 {

    }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM