鏈接到整個項目(不nodes_modules) https://www.dropbox.com/s/4qd8x97ih1f1nho/workinghw4zipped%20%281%29.zip?dl=0Angular2的Javascript驗證輸入數字而不是字符
注意:一旦你運行它,關於這個問題的一切是網站的「編輯所有」部分中,按一下訪問表格
這部分網站的目的是讓用戶輸入表格中每一行的名稱和價格。
如果用戶在價格框內輸入一個字符(不是數字),那麼必須有一個「無效輸入」消息,在用戶輸入時更新自己。
我應該在代碼中添加或更改哪些內容,以便在價格框中輸入字符(而非數字)時允許用戶輸入「無效輸入」消息?
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; }
}
輸入類型使用isNaN函數是一個數字,它仍然接受字符找到ISNUMBER? –
「input type =」number「」應該「阻止」用戶輸入字符,但我仍然想要一種方式向用戶發送消息,以防他們在價格字段中輸入字符 – erin