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

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

问题描述

我正在构建一个角度应用程序,我已经设置了一些表单。
我有一些字段需要在提交前填写。因此我在其上添加了'required':

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-无效'和'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.

我如何确保不会立即添加2个类,但是一旦用户提交了表单或者他在相应的字段中输入了错误的内容?

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)和somet重置为pristine hing尚未输入且无效,则文本将变为 red

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-有效模式 - 当 ng-pattern 传递时,
ng-dirty - 当表单加载了表单后输入了一些内容

ng-pristine - 表单输入自加载后没有插入任何内容(或它是通过表单上的 setPristine(true)重置的。

ng-invalid - 当任何验证失败(必需 minlength ,自定义等)

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-< name> 创造了。

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

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

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