javascript - 如何在angular js中验证两个不同的模型
问题描述
谁能告诉我如何在angularjs中验证两个不同的模型
这是我的代码:
http://plnkr.co/edit/Utsg7Zr8fsg7zzX5Naib?p=preview我正在使用自定义指令添加自定义验证
要求
当用户输入“名字”时它应该显示错误它检查“姓氏”长度如果它小于4。它应该显示错误。如果用户输入“姓氏”则在姓氏中相同然后检查“名字”长度小于4 .如果是,它应该显示错误
我执行以下步骤:
- 在第一个字段中输入“a”(它变成红色很好)。
但是当我在姓氏中输入“abcderff”时,为什么名字是红色的?
.directive("testfirst", function() { return { restrict: "A", require: 'ngModel', link: function(scope, element, attributes, modelVal) { modelVal.$validators.testfirst= function(val) { console.log(attributes.last) console.log((attributes.last && attributes.last.length < 4)); if(val.length > 0 && !(attributes.last && attributes.last.length < 4)){ return false } return true }; scope.$watch("val", function() { modelVal.$validate(); }); } }; }).directive("testlast", function() { return { restrict: "A", require: 'ngModel', link: function(scope, element, attributes, modelVal) { modelVal.$validators.testlast= function(val) { if(val.length > 0 && !(attributes.first && attributes.first.length < 4)){ return false } return true }; scope.$watch("val", function() { modelVal.$validate(); }); } }; });
解决方案
您可以参考我更改此内容:
索引.html
<body ng-controller="MainCtrl">
<button ng-click="submit()">Submit</button>
<form name="myform">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th width="50%">Field Name</th>
<th class="smallcol" width="50%">Field Value</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(key, value) in c">
<td ng-if="value.type == 'LABEL'" colspan="2" style="background: #777; color: white;">{{key}}</td>
<td ng-if="value.type == 'FIELD'">{{key}}</td>
<td ng-if="value.type == 'FIELD' && isEditableMode && value.editable && value.dataType=='last'">
<div class="form-group" ng-class="{'has-error': myform[key].$invalid}">
<input type="text" name="{{key}}" first="{{getCheck('First')}}" class="form-control" ng-model="value.value" ng-keyup="update(value)" testlast>
</div>
</td>
<td ng-if="value.type == 'FIELD' && isEditableMode && value.editable && value.dataType=='name'">
<div class="form-group" ng-class="{'has-error': myform[key].$invalid}">
<input type="text" last="{{getCheck('Last')}}" name="{{key}}" class="form-control" ng-model="value.value" ng-keyup="update(value)" testfirst>
</div>
</td>
</tr>
</tbody>
</table>
</form>
</body>
著名的 :
测试用例1:当用户输入“名字”时它应该显示错误它检查“姓氏”长度如果它小于4。它应该显示错误
测试用例 2:如果用户输入“姓氏”,则姓氏相同,然后检查“名字”长度是否小于 4。如果是,则应显示错误
测试用例 1 完成之后,您必须清除所有字段的值。之后您将测试用例 2,因为 css 显示错误错误。你应该再处理一次。
推荐阅读
- r - 太多滚动条闪亮的rhandsontable
- vue.js - 如何根据 vue-router 中的查询参数更新我的数据
- heroku - 如何运行 Heroku 服务器 24/7
- c# - SSIS 脚本任务 Excel 连接打开:调用目标已引发异常
- c++ - 将小数转换为分数
- c# - 有人可以在 Codewars 上解释这个答案吗?
- python - 如何将 ID 搜索字段转换为项目名称搜索字段?
- c++ - C++ 意外调用基类?
- java - Google Cloud App Engine 上的 Spring Boot 托管
- java - 必须导入什么 cell.setVerticalAlignment(Element.ALIGN_MIDDLE) 才能工作?