【发布时间】:2016-12-13 10:48:45
【问题描述】:
我有 Custom input component with validation 和 ngMessages,FormController 和 ng-required:
<div class="col-sm-9 col-xs-12">
<input
id="{{$ctrl.fieldName}}"
name="{{$ctrl.fieldName}}"
class="form-control"
type="text"
minlength="{{$ctrl.minLength}}"
maxlength="{{$ctrl.maxLength}}"
ng-required="{{$ctrl.isRequired === 'true'}}"
ng-model="$ctrl.value"
ng-change="$ctrl.form.$submitted = false;"
>
<div
ng-messages="$ctrl.form[$ctrl.fieldName].$error"
ng-if="$ctrl.form.$submitted"
>
<span class="help-block" ng-message="required">
Field is required
</span>
<span class="help-block" ng-message="minlength">
Minimum length of field: {{$ctrl.minLength}}
</span>
<span class="help-block" ng-message="maxlength">
Maximum length of field: {{$ctrl.maxLength}}
</span>
</div>
</div>
这样用的:
<act-text-field
form="heroAddForm"
field-name="name"
min-length="3"
max-length="15"
is-required="true"
errors="$ctrl.errors.name"
ng-model="$ctrl.hero.name">
</act-text-field>
我想要实现的是当用户单击submit 按钮时触发验证。它有效,验证也适用于必填字段name,但也适用于不需要的字段description:
<act-text-field
form="heroAddForm"
field-name="description"
max-length="50"
is-required="false"
errors="$ctrl.errors.description"
ng-model="$ctrl.hero.description"
></act-text-field>
对于这个字段,验证消息也是可见的,虽然字段description 是有效的,因为我将has-error 类添加到无效字段:
<div class="form-group"
ng-class="{'has-error': $ctrl.form.$submitted && (!$ctrl.form[$ctrl.fieldName].$valid)}"
>
<!-- rest of code -->
您可以在我的Plunker: Custom input demo app with validation states 中轻松重现此错误行为(我知道它还有其他错误)。我认为ng-message="required" 不应该是可见的,因为字段description 不是必需的。我知道我可以在代码中添加一些ng-ifs 来绕过它,但我认为我在看不到的地方犯了错误。你看到我哪里做错了吗?提前感谢您的每一个帮助。
【问题讨论】:
标签: javascript html angularjs angularjs-validation ng-messages