Ionic 2 RegEX验证不起作用

时间:2017-01-17 17:34:54

标签: validation angular typescript ionic2

我正在尝试验证一个输入字段,该字段应该只允许大于零的正数,为此我使用Validators.compose()一些规则。问题是我无法验证此字段,不知何故它无法按预期工作。难道我做错了什么?我该怎么办呢?感谢

TypeScript代码:

export class SignupPage {
    public signup: FormGroup;

    constructor(public navCtrl: NavController, public navParams: NavParams, public formBuilder: FormBuilder) {
        // setting up sign up form
        this.signup = formBuilder.group({
            "name": ["", Validators.required],
            "age": ["", Validators.compose([Validators.required, Validators.pattern('^[1-9]\d*$')])],
            "city": ["", Validators.required]
        })
    }

    onSubnmit(form) {
        console.log(form);

        let user = {
            'name': form.name,
            'age': form.age,
            'city': form.city
        }
    }

HTML代码:

<form [formGroup]="signup" (ngSubmit)="onSubmit(this.signup.value)">
    <ion-list class="signup-input">
        <ion-item>
            <ion-label floating>What is your name?</ion-label>
            <ion-input type="text" formControlName="name" [class.invalid]="!signup.valid && (signup.controls.name.dirty || submitAttempt)"></ion-input>
        </ion-item>
        <ion-item *ngIf="!signup.controls.name.valid && (signup.controls.name.dirty || submitAttempt)" >
            <small>Please fill out this field.</small>
        </ion-item>

        <ion-item>
            <ion-label floating>How old are you?</ion-label>
            <ion-input type="text" formControlNale="age" [class.invalid]="!signup.controls.age.valid && (signup.controls.age.dirty || submitAttempt)"></ion-input>
        </ion-item>
        <ion-item *ngIf="!signup.controls.age.valid && (signup.controls.age.dirty || submitAttempt)" >
            <small>Please enter a valid age.</small>
        </ion-item>

        <ion-item>
            <ion-label floating>What is your city?</ion-label>
            <ion-input type="text" formControlName="city" [class.invalid]="!signup.controls.city.valid && (signup.controls.city.dirty || submitAttempt)"></ion-input>
        </ion-item>
        <ion-item *ngIf="!signup.controls.city.valid && (signup.controls.city.dirty || submitAttempt)" >
            <small>Please fill out this field.</small>
        </ion-item>

    </ion-list>
    <ion-grid>
        <ion-row>
            <div class="signup-btn">
                <button ion-button block width-90 type="submit" [disabled]="!this.signup.valid">Get in</button>
            </div>
        </ion-row>
    </ion-grid>
</form>

这就是它的样子:

Result

1 个答案:

答案 0 :(得分:3)

指令名称中的错字

formControlNale="age"

应该是

formControlName="age"