响应式/模型驱动的表单 - 验证响应式表单

优质
小牛编辑
116浏览
2023-12-01

Angular 2提供了开箱即用的许多验证器。 它们可以与其余的依赖关系一起导入。

app/login-form.component.html

  1. <div>
  2. <label for="username">username</label>
  3. <input
  4. type="text"
  5. name="username"
  6. id="username"
  7. [formControl]="username">
  8. <div [hidden]="username.valid || username.untouched">
  9. <div>
  10. The following problems have been found with the username:
  11. <div [hidden]="!username.hasError('minlength')">
  12. Username can not be shorter than 5 characters.
  13. </div>
  14. <div [hidden]="!username.hasError('required')">
  15. Username is required.
  16. </div>
  17. </div>
  18. </div>
  19. <div >
  20. <label for="password">password</label>
  21. <input
  22. type="password"
  23. name="password"
  24. <div [hidden]="password.valid || password.untouched">
  25. <div>
  26. The following problems have been found with the password:
  27. </div>
  28. <div [hidden]="!password.hasError('required')">
  29. The password is required.
  30. </div>
  31. </div>
  32. </div>
  33. <button type="submit" [disabled]="!loginForm.valid">Log In</button>
  34. </form>

对于内置验证,我们在表单元素上调用.hasError(),我们传递一个字符串,它表示我们包含的验证器函数。 仅当此测试返回true时,才会显示错误消息。