如何在打字稿中单击按钮时显示验证 [英] How to show validation on button click in typescript
本文介绍了如何在打字稿中单击按钮时显示验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想显示对空白字段的验证,为此我使用了以下方法,但是它不起作用.有人可以建议我帮忙.
I want to show up validation for the fields which are empty and for that i used the following method but its not working.Can anyone suggest me help.Thanks.
我的模板
<form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" class="nobottommargin adminloginform" novalidate>
<label class="col-sm-4 text-right norightpadding">First Name</label>
<div class="input-group" [ngClass]="{errmsg: (!form.controls['password'].valid ||
(!form.controls['password'].pristine && submitted ))}">
<input type="text" [formControl]="form.controls['lastname']" >
</div>
<div class="col-sm-8">
<button type="submit" >Register now</button>
</div>
我的ts
export class SignUp {
submitted: boolean = false;
constructor(public fbld: FormBuilder, http: Http, public config: Config, public router: Router) {
this.http = http;
this.form = fbld.group({
firstname: ['', Validators.required],
});
this.header = this.config.header1;
}
onSubmit(form: ISignup): any {
this.submitted = true;
}
}
推荐答案
请检查以下解决方案.
DEMO: https://plnkr.co/edit/mJFftirG3ATDpnJRWmKN?p=preview
export class AppComponent {
form: FormGroup;
constructor(private formBuilder: FormBuilder){
this.submitted=false;
this.form = formBuilder.group({
lastname: ['', Validators.required],
});
}
onSubmit(form)
{
this.submitted=true;
console.log(form);
if(form.valid) //<<<### submit form is it is valid only
{
console.log('form submitted');
}
}
}
这篇关于如何在打字稿中单击按钮时显示验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文