Angularjs - 如果条件,则必填字段

时间:2016-05-12 14:45:17

标签: angularjs

我正在使用angular-messages.min.js进行验证。

我有下一个网络表单:

<form role="form" name="form">
    <div class="col-md-12">
        <div class="form-group col-xs-4 col-md-4">
                <label class="control-label">Field1</label>
                <select class="form-control" name="field1" ng-model="field1" ng-options="item for item in device" ng-change="deviceChange();"></select>
        </div>
        <div class="form-group col-xs-2 col-md-2">
                <label class="control-label">Field2</label>
                <select class="form-control" name="field2" ng-model="field2" ng-options="item for item in use"></select>
        </div>
        <div class="form-group col-xs-6 col-md-6" ng-class="{ 'has-error': form.field1.$invalid && form.field2.$invalid }">
                <label class="control-label">Field3</label>
                <input type="text" class="form-control" name="field3" ng-model="field3" />
                <div class="help-block" ng-messages="form.field3.$error" ng-if="form.field3.$touched">
                    <p ng-message="required">Your field3 is required</p>
                </div>
        </div>
    </div>
</form>

字段field1,field2和field3不是必需的,但如果field1和field2有内容,则field3是必填字段。

如何在field3中显示验证消息?感谢,

1 个答案:

答案 0 :(得分:2)

这应该有所帮助:

 <input type="text" class="form-control" name="field3" ng-required="field1 && field2" ng-model="field3" />