phan ngoc
phan ngoc

Reputation: 191

How to validate form angular with attribute in object?

This is code we can validate in normal function:

<p>Username:<br>
  <input type="text" name="username" ng-model="username" required>
  <span style="color:red" ng-show="articleForm.username.$dirty && articleForm.username.$invalid">
  <span ng-show="articleForm.username.$error.required">Username is required.</span>
  </span>
</p>

But when I have title field that have code:

<header class="list-group-item-text">
  <label>Title</label>
  <input type="text" name="title" ng-model="$parent.mopost.title" class="form-control" required>
  <span class="help-inline" ng-show="articleForm.$parent.mopost.title.$error.required">Required</span>
</header>

And controller:

$scope.mopost = {title:"",content1:"",content2:"",linkaudio:""};

Now validate in Angular, it does not operate. How I can validate attribute of object same above.

Upvotes: 0

Views: 793

Answers (1)

Sengottaian Karthik
Sengottaian Karthik

Reputation: 398

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body>

  <h2>Validation</h2>

  <form ng-app="myApp" ng-controller="demoCtrl" name="articleForm" novalidate>
    <header class="list-group-item-text">
      <label for="title">Title</label>
      <input id="title" type="text" name="user" ng-model="user" class="form-control" required>
      <span ng-show="articleForm.user.$error.required">Username is required.</span>
    </header>

    <input type="submit" ng-disabled="articleForm.user.$dirty && articleForm.user.$invalid ||  
                                          articleForm.email.$dirty && articleForm.email.$invalid">
  </form>

  <script>
    var app = angular.module('myApp', []);
    app.controller('demoCtrl', function($scope) {
      $scope.title = '';
    });
  </script>

</body>

</html>

Upvotes: 1

Related Questions