如何在角度中形成验证联合下拉菜单?

时间:2015-09-03 17:03:16

标签: javascript angularjs

HTML:

<form name="loginForm" ng-submit="submit()" novalidate>
    <select name="Month" ng-required="true" ng-model="dob.Month">
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </select>

    <select name="Year" ng-required="true" ng-model="dob.Year">
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </select>
</form>

我希望错误消息(月,年需要选择!)

有类似的东西:

<span ng-if="loginForm.Year.$error.required">This is required!</span>
<span ng-if="loginForm.Month.$error.required">This is required!</span>

但我希望错误消息(月,年需要选择!)

有没有办法为这些选择菜单创建forloop并查看它们是否无效 - 是否必需?

2 个答案:

答案 0 :(得分:0)

您可以在表单上进行验证

<span ng-if="loginForm.$invalid">Month, Year needs to be selected!</span>

Demo Plunkr

答案 1 :(得分:0)

如果您希望在月份或年份无效时显示相同的错误消息,则可以将上述两条错误消息合并为一条消息,如下所示:

<span ng-if="loginForm.Year.$error.required || loginForm.Month.$error.required">
     Month and Year need to be selected!
</span>

如果未选中,或者如果选择了一个而另一个未选中,则会显示错误消息。

修改

要实现所需的行为,您应该有三个具有不同ng-if条件的单独错误消息,如下所示:

<p>
  <span ng-if="selectsForm.month.$error.required && selectsForm.year.$error.required">Month and year must be selected!</span>
  <span ng-if="selectsForm.$dirty && (selectsForm.month.$error.required || !selectsForm.year.$error)">Month needs to be selected!</span>
  <span ng-if="selectsForm.$dirty && (selectsForm.year.$error.required || !selectsForm.month.$error)">Year needs to be selected!</span>
</p>