Checking json input using angularjs

I want to check JSON input. I know that this can be done using a special directive, but I can not write it myself. Now I am trying to do this with ng-change.

my html:

<div class="row">
    <div class="form-group col-xs-12">
         <label>Custom data:</label>
         <textarea class="form-control" rows="10" name="customData" ng-model="application.customDataString" ng-change="validateJSON()"></textarea>
    </div>
 </div>

my script

$scope.validateJSON = function () {
        try {
            JSON.parse($scope.application.customDataString);
        } catch (e) {
            $scope.applicationForm.customData.$setValidity = false;
        }
        return true;
}

but I get an error: I can not read the property $ setValidity 'undefined

+4
source share
1 answer

check this

var app = angular.module('myApp', []);
    app.controller('mainCtrl', function($scope) {

      $scope.application = {
        customDataString: ""
      };

      $scope.validateJSON = function() {

        try {
          JSON.parse($scope.application.customDataString);
          $scope.myForm.customData.$valid = true;
          // or
          // myForm.customData.$setValidity('valid', true);
        } catch (e) {
          $scope.myForm.customData.$valid = false;
           // or
           // myForm.customData.$setValidity('valid', false);
        }
        return true;
      }

    })
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <script data-require="angular.js@1.6.5" data-semver="1.6.5" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-controller="mainCtrl">

  <div class="row" name="myForm" ng-form>
    <div class="form-group col-xs-12">
      <label>Custom data:</label>
      <textarea class="form-control" rows="10" name="customData" ng-form ng-model="application.customDataString" ng-change="validateJSON(myForm)"></textarea>
    </div>
  </div>
  <br>
  IS JSON VALID: {{myForm.customData.$valid}}
</body>

</html>
Run code

Check out this plunker. Using ng-form https://plnkr.co/edit/0BFO08fYU0op6z2W9Vh4?p=preview

+1
source

Source: https://habr.com/ru/post/1686025/


All Articles