我正在尝试创建一个联系表单。该表单如下:
<form novalidate [formGroup]="contact" (ngSubmit)="send()">
<p>
<label>Name
<br>
<input type="text" class="input" value="" formControlName="name">
<span class="error">Enter your name</span>
</label>
</p>
<p>
<label>E-mail
<br>
<input type="email" class="input" value="" formControlName="email">
<span class="error">It looks like this email is invalid</span>
</label>
</p>
<p>
<label>Phone
<br>
<input type="text" class="input" value="" formControlName="telefone">
<span class="error">It looks like this phone number is invalid</span>
</label>
</p>
<p>
<label>Message
<br>
<textarea type="text" class="input" value="" formControlName="message"></textarea>
<span class="error">The message can't be empty</span>
</label>
</p>
<p class="submit">
<input type="submit" name="submit" class="bt" value="Send">
</p>
</form>
在这个表单中,只有消息、姓名和电子邮件或电话号码字段应该是必填的。
我正在使用一个formBuilder
类,所以这里是TypeScript代码:
this.contact = this.formBuilder.group({
name: ['', Validators.required],
email: ['', Validators.compose([/*Use custom validador??*/])],
phone: ['', Validators.compose([/*Use custom validador??*/]],
message: ['', Validators.required]
});
我尝试使用自定义验证器作为解决方案,但是我无法找到解决方法。有什么建议吗?
nameLengthFive
,请记住在FormGroup
上调用hasError
,而不是FormControl
。正如所写的答案一样,您已经做对了,只是很容易忽略。 - Kent Bull