如果验证有效,则输入角度切换类

时间:2016-12-13 10:44:02

标签: angularjs validation

如果验证有效,我试图在输入上切换css类,如果无效,我可以这样做,但如果有效则需要两个类,如果不是,则需要两个类。如果无效,它是否容易制作,但如果添加if是有效的,这是我现在的代码:

<form name="userForm" ng-submit="submitForm()" novalidate>
    <input type="email" name="email" placeholder="E-mailadres" class="input-field" ng-model="user.email" required ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$pristine }" />
    <p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p>
    <input type="password" name="password" ng-model="user.password" placeholder="Wachtwoord" class="input-field" required />
    <p ng-show="userForm.password.$invalid && !userForm.password.$pristine" class="help-block">You name is required.</p>
    <button type="submit" class="btn hit-btn" ng-disabled="userForm.$invalid">Log in</button>
</form>

您会注意到我的课程有错误,但我还需要课无错误

3 个答案:

答案 0 :(得分:2)

试试这个......

&#13;
&#13;
.has-error {
  background: red;
}
.no-error {
  background: green;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app>
  <form name="userForm" ng-submit="submitForm()" novalidate>
    <input type="email" name="email" placeholder="E-mailadres" class="input-field" ng-model="user.email" required ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$pristine,'no-error' :!userForm.email.$invalid }" />
    <p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p>
    <input type="password" name="password" ng-model="user.password" placeholder="Wachtwoord" class="input-field" required />
    <p ng-show="userForm.password.$invalid && !userForm.password.$pristine" class="help-block">You name is required.</p>
    <button type="submit" class="btn hit-btn" ng-disabled="userForm.$invalid">Log in</button>
  </form>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果你需要另一个类,只需添加相反的条件:

<input type="email" name="email" placeholder="E-mailadres"
  class="input-field" ng-model="user.email" required
  ng-class="{
     'has-error' : userForm.email.$invalid && !userForm.email.$pristine, 
     'no-error' : !userForm.email.$invalid || userForm.email.$pristine 
  }"
/>

答案 2 :(得分:0)

 ng-class="{userForm.email.$invalid && !userForm.email.$pristine?'has-error':'no-error'}"