Node Newbie
Node Newbie

Reputation: 1971

Validation in AngularJS

I am new to AngularJS. I am trying to implement some validation. As a test, I'm looking at a basic login screen. The code for that login screen looks like the following:

<style type="text/css">
  input.ng-invalid.ng-dirty { background-color: red; color:white; }
</style>

<form novalidate name="loginForm" role="form">
  <div ng-show="(isDataValid==false)" class="ng-hide">
    Please correct the errors on the page.
  </div>

  <div>
    <label for="username">Username</label>
    <input type="text" id="username" placeholder="Username" ng-model="username"
           required>
  </div>

  <div>
    <label for="password">Password</label>
    <input type="password" id="password" placeholder="Password" ng-model="password"
           required>
  </div>

  <button type="submit" ng-click="formSubmit(loginForm);">Submit</button>
</form>

<script type="text/javascript">
  function loginController($scope) {
    $scope.isDataValid = null;

    $scope.formSubmit = function(f) {
      $scope.isDataValid = f.$valid;
      if (f.$invalid) {
        return;
      }

      return false;
    };
  }
</script>

When the page loads up, I want it to be in a clean looking state (this works). I want field level validation after a user begins working with a field (this works). I want field level validation when a user clicks 'submit'. This partially works.

My problem is, if I press 'submit' without using the fields at all, the css classes on the fields do not get updated. I believe the reason why is because the fields aren't 'dirty'. However, I'm not sure how to fix this and 1) meet my first requirement and 2) Adhere to the idea of keeping AngularJS controlls away from the DOM.

Does anyone know how I can do this?

Thank you so much!

Upvotes: 1

Views: 595

Answers (1)

m.e.conroy
m.e.conroy

Reputation: 3538

I commented on your post but figured I should show an example.

 <button type="button" class="btn btn-primary btn-lg" ng-click="submit()" ng-disabled="(createContacts.$dirty && createContacts.$invalid) || createContacts.$pristine"><span class="icon-save"></span> Save Contacts</button>

This is a "submit" button I used in a form named "createContacts." The user is unable to use this button when the form is in its "pristine" state (when nothing has been entered) and when the form is "dirty" and "invalid" (information has been entered but the form has validation errors).

http://jsfiddle.net/Ddb4M/

Upvotes: 1

Related Questions