使用angularjs进行json输入验证

时间:2017-09-20 09:38:04

标签: angularjs json

我想验证JSON输入。我知道它可以用自定义指令完成,但我不能自己编写它。现在我正试着用ng-change来做。

我的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>

我的剧本

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

但我收到错误:无法读取属性&#39; $ setValidity&#39;未定义的

1 个答案:

答案 0 :(得分:2)

检查

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>

也检查这个plunker。使用ng-form https://plnkr.co/edit/0BFO08fYU0op6z2W9Vh4?p=preview