1

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!

2
  • This would help you jsfiddle.net/thomporter/ANxmv/2 Commented Oct 11, 2013 at 13:01
  • Disable the submit button till the form is $dirty and the fields are $valid Commented Oct 11, 2013 at 13:31

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.