响应式/模型驱动的表单 - 验证响应式表单
优质
小牛编辑
143浏览
2023-12-01
Angular 2提供了开箱即用的许多验证器。 它们可以与其余的依赖关系一起导入。
app/login-form.component.html
<div>
<label for="username">username</label>
<input
type="text"
name="username"
id="username"
[formControl]="username">
<div [hidden]="username.valid || username.untouched">
<div>
The following problems have been found with the username:
<div [hidden]="!username.hasError('minlength')">
Username can not be shorter than 5 characters.
</div>
<div [hidden]="!username.hasError('required')">
Username is required.
</div>
</div>
</div>
<div >
<label for="password">password</label>
<input
type="password"
name="password"
<div [hidden]="password.valid || password.untouched">
<div>
The following problems have been found with the password:
</div>
<div [hidden]="!password.hasError('required')">
The password is required.
</div>
</div>
</div>
<button type="submit" [disabled]="!loginForm.valid">Log In</button>
</form>
对于内置验证,我们在表单元素上调用.hasError()
,我们传递一个字符串,它表示我们包含的验证器函数。 仅当此测试返回true时,才会显示错误消息。