Angular JS form validation in "myApp" application.

116 Views Asked by At

I am new to AngularJS and try to implement form validation in "myApp" app. I wrote the code below. The {{result}} should output "true"/"false". But it didn't work.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
 <form name = "myForm">
     <p>Input the field: </p>
        <input type = "text" name="myInput" ng-model = "myInput" required>
     </form>
        <p> The result:</p>
        <p>{{result}}</p>
        
    <script>
     var app = angular.module("myApp", []);
        app.controller("myCtrl", function($scope){
   $scope.result = myForm.myInput.$valid;
  });
    </script>
</body>

2

There are 2 best solutions below

1
ChamalPradeep On BEST ANSWER

This must be correct code for your problem. If you "watch" the changes in the "input field" then $valid result will generate.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="MyController"> 
            <form name='myForm' novalidate>
            <p>Input the field: </p>
             <input type='text' ng-model='model.name' name='myInput' required/> 
            </form>
            <p> The result:</p>
            <p>{{myForm.myInput.$valid}}</p>
    <script> 
        var app = angular.module('myApp', []);
            app.controller('MyController',['$scope',function($scope) {
                $scope.$watch('myForm.myInput.$valid',function(newValue,oldvalue) {
                if(newValue) { 
                    //do anything with new value
                }
            });
        }]); 
    </script>
</body>
</html>

Hope this will be helpful to you.

2
ChamalPradeep On

As a new User to angularJS your approcach is some how correct in form validation.In future you will learn new vesions in angular and several validation methodologies. following code line is the way that how we can check valid input in angularJS.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>  
<body ng-app="">

<p>Try writing in the input field:</p>

<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>

<p>The input's valid state is:</p>
<h1>{{myForm.myInput.$valid}}</h1>

</body>
</html>

Your approach is correct.Keep it up and it will be great if you can define correct question clearly. :) Cheers.