Angular 会在“必填"字段上自动添加“ng-invalid"类 [英] Angular is automatically adding 'ng-invalid' class on 'required' fields

查看:32
本文介绍了Angular 会在“必填"字段上自动添加“ng-invalid"类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 angular 应用程序,我为其设置了一些表单.我有一些字段需要在提交前填写.因此,我在它们上面添加了必需":

I am building an angular app for which I have some forms set up. I have some fields that are required to be filled before submission. Therefore I have added 'required' on them:

<input type="text" class="form-control" placeholder="Test" ng-model="data.test" required>

但是,当我启动我的应用程序时,即使在点击提交按钮或用户输入任何内容之前,字段都显示为无效"和类ng-invalid"和ng-invalid-required"字段.

However when I launch my app, the fields are displayed as 'invalid' and the classes 'ng-invalid' and 'ng-invalid-required' even before the submit button has been click or before the user has typed anything in the fields.

如何确保不会立即添加这两个类,而是在用户提交表单或在相应字段中输入错误时添加?

How can I make sure that thoses 2 classes are not added immediately but either once the user has submitted the form or when he has typed something wrong in the corresponding field?

推荐答案

由于输入为空,因此实例化时无效,Angular 正确添加了 ng-invalid 类.

Since the inputs are empty and therefore invalid when instantiated, Angular correctly adds the ng-invalid class.

您可以尝试的 CSS 规则:

A CSS rule you might try:

input.ng-dirty.ng-invalid {
  color: red
}

这基本上说明了自页面加载以来该字段何时在某个时间点输入了某些内容并且没有被 $scope.formName.setPristine(true) 重置为原始状态,并且某些内容不是't 尚未输入且无效然后文本变为红色.

Which basically states when the field has had something entered into it at some point since the page loaded and wasn't reset to pristine by $scope.formName.setPristine(true) and something wasn't yet entered and it's invalid then the text turns red.

Angular 表单的其他有用类(请参阅 输入以供将来参考)

Other useful classes for Angular forms (see input for future reference )

ng-valid-maxlength - 当 ng-maxlength 通过时
ng-valid-minlength - 当 ng-minlength 通过时
ng-valid-pattern - 当 ng-pattern 通过时
ng-dirty - 当表单加载了一些东西时
ng-pristine - 当表单输入自加载后没有插入任何内容时(或者通过表单上的 setPristine(true) 重置)
ng-invalid - 当任何验证失败时(requiredminlength、自定义的等等)

ng-valid-maxlength - when ng-maxlength passes
ng-valid-minlength - when ng-minlength passes
ng-valid-pattern - when ng-pattern passes
ng-dirty - when the form has had something entered since the form loaded
ng-pristine - when the form input has had nothing inserted since loaded (or it was reset via setPristine(true) on the form)
ng-invalid - when any validation fails (required, minlength, custom ones, etc)

同样,对于所有这些模式和创建的任何自定义模式,还有 ng-invalid-.

Likewise there is also ng-invalid-<name> for all these patterns and any custom ones created.

这篇关于Angular 会在“必填"字段上自动添加“ng-invalid"类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆