Angular会自动添加'ng- invalidate '类'要求'字段
Angular is automatically adding 'ng-invalid' class on 'required' fields
我正在构建一个angular应用程序,我有一些形式设置。我有一些字段是需要填写提交前。因此,我在它们上面添加了'required':
<input type="text" class="form-control" placeholder="Test" ng-model="data.test" required>
然而,当我启动我的应用程序时,字段显示为'invalid',类'ng-invalid'和'ng-invalid-required'甚至在提交按钮被点击或用户在字段中键入任何内容之前。
我怎样才能确保这2类不立即添加,但一旦用户提交了表单或当他在相应的字段中输入了错误的东西?
由于输入为空,因此在实例化时无效,Angular会正确添加ng-invalid
类。
一个你可以尝试的CSS规则:
input.ng-dirty.ng-invalid {
color: red
}
这基本上表示当字段在页面加载后的某个时刻输入了一些东西,并且没有被$scope.formName.setPristine(true)
重置为原始状态,并且还没有输入一些东西并且它是无效的,然后文本变为red
。
其他有用的Angular表单类(参见输入以供将来参考)
ng-valid-maxlength
-当ng-maxlength
通过ng-valid-minlength
-当ng-minlength
通过时ng-valid-pattern
-当ng-pattern
通过时ng-dirty
-当表单加载了
后输入了一些内容时ng-pristine
-当表单输入自加载以来没有插入任何内容(或通过表单上的setPristine(true)
重置)ng-invalid
-当任何验证失败时(required
, minlength
,自定义等)
同样也有ng-invalid-<name>
所有这些模式和任何自定义的创建。
多亏了这篇文章,我用这个样式删除了在显示必填字段时自动出现的红色边框,但是用户没有机会输入任何东西:
input.ng-pristine.ng-invalid {
-webkit-box-shadow: none;
-ms-box-shadow: none;
box-shadow:none;
}
由于字段为空,它们无效,因此ng-invalid
和ng-invalid-required
类被正确添加。
您可以使用ng-pristine
类来检查字段是否已经被使用。
尝试在提交表单或字段无效时动态添加类进行验证。使用表单名称并将'name'属性添加到输入。带有Bootstrap的示例:
<div class="form-group" ng-class="{'has-error': myForm.$submitted && (myForm.username.$invalid && !myForm.username.$pristine)}">
<label class="col-sm-2 control-label" for="username">Username*</label>
<div class="col-sm-10 col-md-9">
<input ng-model="data.username" id="username" name="username" type="text" class="form-control input-md" required>
</div>
</div>
同样重要的是,您的表单具有ng-submit="属性:
<form name="myForm" ng-submit="checkSubmit()" novalidate>
<!-- input fields here -->
....
<button type="submit">Submit</button>
</form>
您还可以为表单添加一个可选的验证函数:
//within your controller (some extras...)
$scope.checkSubmit = function () {
if ($scope.myForm.$valid) {
alert('All good...'); //next step!
}
else {
alert('Not all fields valid! Do something...');
}
}
现在,当你加载你的应用程序时,类'has-error'只会在表单被提交或字段被触摸时添加。而不是:
! myForm.username。美元的
你也可以使用:
myForm.username。美元脏
接受的答案是正确的。对于移动设备,你也可以使用这个(ng-touched rather ng-dirty)
input.ng-invalid.ng-touched{
border-bottom: 1px solid #e74c3c !important;
}
- 要求输入在数据列表中
- 要求未定义JS回调参数
- 当脚本由system.js加载时,如何要求('electron')
- 要求定义另一个文件中的对象
- 这是什么“;要求“;事情
- 为什么spyOn"停止函数“”的所有执行;Jasmine(要求澄清Jasmine 2.2间谍文件)
- AMD格式是否要求模块为单件
- 如何在nodejs中要求类
- 当浏览器控制台未打开时,为什么要求会导致Internet Explorer 9超时
- 这个代码在网页中的作用和要求是什么
- Last.fm API发送2个曲目时,我要求一个,如果我正在听一首歌
- 在离开Aurelia.js上的页面之前,我如何要求用户进行确认
- 要求创建空模块作为依赖项加载程序
- 下拉列表没有'当添加'要求'到'敲除'
- 申请表要求在提交前一个单元格与其他单元格相等
- Visual Studio 2015 Update 2-'中的TypeScript模块;要求'未定义
- HTML5要求隐藏文件字段-反馈位置
- 有没有人能够得到这个要求或调试NPM模块在浏览器中工作
- 我如何使用 webpack 从控制台要求()
- Angular会自动添加'ng- invalidate '类'要求'字段