我有一个基于Angular的表单,我想要应用特定的验证:
<form name="createProject" novalidate>
<span ng-show="createProject.projectName.$invalid">Please enter a name for the project.</span></br>
<input type="text" ng-model="newProject.project.name" name="projectName" placeholder="Project Name" required>
<div ng-repeat="topic in newProject.project.topics_attributes">
<span>Topic {{$index + 1}}</span>
<input type="text" ng-model="topic.name" placeholder="Topic Name">
<input type="text" ng-model="topic.feed_size">
<div ng-repeat="topic_source in topic.topic_sources_attributes">
<span>Topic {{$parent.$index + 1}} Source {{$index + 1}}</span>
<select ng-model="topic_source.platform" ng-options="platform for platform in platforms" topic-source-required parent="$parent.topic.name">
<option value="">-- platform --</option>
</select>
<input type="text" ng-model="topic_source.keywords" placeholder="Topic Keywords" topic-source-required parent="$parent.topic.name">
<button ng-show="$last" ng-click="addTopicSource($parent.topic)">Add Topic Source</button>
</div>
</div>
<button ng-click="addTopic()">New Topic</button>
<input type="submit" ng-click="addProject()" ng-class="{ disabled: createProject.$invalid }" ng-disabled="createProject.$invalid" value="Add Project">
</form>
<a href="#">Back</a>
在表单中,项目可以包含零个或多个主题。每个主题必须至少有一个主题源。基本上,我想创建验证,检查是否添加了主题(添加被定义为具有名称),如果需要,则要求它至少有一个topic_source,其中输入了与之关联的平台和关键字字段。
这甚至可能吗?我对Angular自定义验证不太熟悉,所以我不确定如何开始实现这样的事情。
** **编辑
自定义验证指令的当前进展:
angular.module('dashboard').directive 'topicSourceRequired', ($parse) ->
require: "ngModel"
link: (scope, elem, attrs, ctrl) ->
topicName = $parse attrs.parent
scope.$watch topicName, (topicName) ->
ctrl.$parsers.unshift checkForExistence if topicName
checkForExistence = (topicSource) ->
if topicSource
ctrl.$setValidity "topicSourceRequired", true
else
ctrl.$setValidity "topicSourceRequired", false
topicSource
好的,接近这个验证。现在,验证似乎是检查两个topic_source字段是否具有与父名称字段是否具有值无关的值,并且如果已输入然后擦除字段,则topic_source字段仅注册为无效。
如何确保仅在topicName具有非空字符串值时调用checkForExistence函数?其次,如何确保空白字段无效,而不必以某种方式修改它们?
答案 0 :(得分:0)
您需要创建一个需要ngModel的自定义指令,它允许您访问ngModelController(在创建指令时查看require选项)。
基本上,您可以通过注册$ viewChangeListeners来监听值的更改,从$ viewValue读取当前值,并通过控制器函数设置验证
$setValidity(validationErrorKey, isValid);
您设置的validationErrorKey是控制器的$ erros对象上的布尔值。
请查看文档中的此页面以帮助您: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController