Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json input validation with angularjs

Tags:

json

angularjs

I want to validate JSON input. I know it can be done with a custom directive, but I am not capable of writing it on my own. Now I am trying to do it 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 am getting an error: Cannot read property '$setValidity' of undefined

like image 475
taskiukas Avatar asked Oct 18 '22 05:10

taskiukas


1 Answers

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="[email protected]" 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>

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

like image 161
Sibiraj Avatar answered Oct 21 '22 03:10

Sibiraj