AngularJS directive for validation











up vote
0
down vote

favorite












I'm trying to make a directive able to handle an <input type="file"> validation inside a <form> given that AngularJS doesn't have support for this...It kind of works to check if a file is selected, but I also have a <textarea> in the form so when I select a file the form gets state $valid=true, but just by typing into the <textarea> makes the form become $valid=false even though I haven't set a validation for the <textarea>. Why does this happen? How can I fix it?. Here is a simplified example to illustrate the problem:





My app.js file:



    var app = angular.module('plunker', );

app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});



app.directive('validFile', function () {
return {
restrict: "A",
require: '^form',

link: function (scope,elem,attrs, ctrl) {

elem.bind("change", function(e) {
console.log("change");
scope.$apply(function(){
ctrl.$valid=true;
ctrl.$invalid=false;
});
});

}
};
});


My index.html file:



    <!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-form="myForm" >
<input ng-model="filename" valid-file required type="file"/>
<button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary"><i class="icon-white icon-ok"></i>&nbsp;Ok</button>
<div >
<textarea name="observations" rows="3" cols="50" ng-model="observations"></textarea>
</div>
<p>
Input is valid: {{myForm.$valid}} Input is invalid: {{myForm.$invalid}}
<br>Selected file: {{filename}}
<br>Area is valid: {{myForm.observations.$valid}} Area is invalid: {{myForm.observations.$invalid}}
</p>
</div>
</body>
</html>


there's a working plnkr of what I just said:
http://plnkr.co/edit/k3KZpdX5q3pelWN21NVp?p=preview










share|improve this question




























    up vote
    0
    down vote

    favorite












    I'm trying to make a directive able to handle an <input type="file"> validation inside a <form> given that AngularJS doesn't have support for this...It kind of works to check if a file is selected, but I also have a <textarea> in the form so when I select a file the form gets state $valid=true, but just by typing into the <textarea> makes the form become $valid=false even though I haven't set a validation for the <textarea>. Why does this happen? How can I fix it?. Here is a simplified example to illustrate the problem:





    My app.js file:



        var app = angular.module('plunker', );

    app.controller('MainCtrl', function($scope) {
    $scope.name = 'World';
    });



    app.directive('validFile', function () {
    return {
    restrict: "A",
    require: '^form',

    link: function (scope,elem,attrs, ctrl) {

    elem.bind("change", function(e) {
    console.log("change");
    scope.$apply(function(){
    ctrl.$valid=true;
    ctrl.$invalid=false;
    });
    });

    }
    };
    });


    My index.html file:



        <!doctype html>
    <html ng-app="plunker" >
    <head>
    <meta charset="utf-8">
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.js"></script>
    <script src="app.js"></script>
    </head>
    <body ng-controller="MainCtrl">
    <div ng-form="myForm" >
    <input ng-model="filename" valid-file required type="file"/>
    <button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary"><i class="icon-white icon-ok"></i>&nbsp;Ok</button>
    <div >
    <textarea name="observations" rows="3" cols="50" ng-model="observations"></textarea>
    </div>
    <p>
    Input is valid: {{myForm.$valid}} Input is invalid: {{myForm.$invalid}}
    <br>Selected file: {{filename}}
    <br>Area is valid: {{myForm.observations.$valid}} Area is invalid: {{myForm.observations.$invalid}}
    </p>
    </div>
    </body>
    </html>


    there's a working plnkr of what I just said:
    http://plnkr.co/edit/k3KZpdX5q3pelWN21NVp?p=preview










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I'm trying to make a directive able to handle an <input type="file"> validation inside a <form> given that AngularJS doesn't have support for this...It kind of works to check if a file is selected, but I also have a <textarea> in the form so when I select a file the form gets state $valid=true, but just by typing into the <textarea> makes the form become $valid=false even though I haven't set a validation for the <textarea>. Why does this happen? How can I fix it?. Here is a simplified example to illustrate the problem:





      My app.js file:



          var app = angular.module('plunker', );

      app.controller('MainCtrl', function($scope) {
      $scope.name = 'World';
      });



      app.directive('validFile', function () {
      return {
      restrict: "A",
      require: '^form',

      link: function (scope,elem,attrs, ctrl) {

      elem.bind("change", function(e) {
      console.log("change");
      scope.$apply(function(){
      ctrl.$valid=true;
      ctrl.$invalid=false;
      });
      });

      }
      };
      });


      My index.html file:



          <!doctype html>
      <html ng-app="plunker" >
      <head>
      <meta charset="utf-8">
      <title>AngularJS Plunker</title>
      <script>document.write('<base href="' + document.location + '" />');</script>
      <link rel="stylesheet" href="style.css">
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.js"></script>
      <script src="app.js"></script>
      </head>
      <body ng-controller="MainCtrl">
      <div ng-form="myForm" >
      <input ng-model="filename" valid-file required type="file"/>
      <button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary"><i class="icon-white icon-ok"></i>&nbsp;Ok</button>
      <div >
      <textarea name="observations" rows="3" cols="50" ng-model="observations"></textarea>
      </div>
      <p>
      Input is valid: {{myForm.$valid}} Input is invalid: {{myForm.$invalid}}
      <br>Selected file: {{filename}}
      <br>Area is valid: {{myForm.observations.$valid}} Area is invalid: {{myForm.observations.$invalid}}
      </p>
      </div>
      </body>
      </html>


      there's a working plnkr of what I just said:
      http://plnkr.co/edit/k3KZpdX5q3pelWN21NVp?p=preview










      share|improve this question















      I'm trying to make a directive able to handle an <input type="file"> validation inside a <form> given that AngularJS doesn't have support for this...It kind of works to check if a file is selected, but I also have a <textarea> in the form so when I select a file the form gets state $valid=true, but just by typing into the <textarea> makes the form become $valid=false even though I haven't set a validation for the <textarea>. Why does this happen? How can I fix it?. Here is a simplified example to illustrate the problem:





      My app.js file:



          var app = angular.module('plunker', );

      app.controller('MainCtrl', function($scope) {
      $scope.name = 'World';
      });



      app.directive('validFile', function () {
      return {
      restrict: "A",
      require: '^form',

      link: function (scope,elem,attrs, ctrl) {

      elem.bind("change", function(e) {
      console.log("change");
      scope.$apply(function(){
      ctrl.$valid=true;
      ctrl.$invalid=false;
      });
      });

      }
      };
      });


      My index.html file:



          <!doctype html>
      <html ng-app="plunker" >
      <head>
      <meta charset="utf-8">
      <title>AngularJS Plunker</title>
      <script>document.write('<base href="' + document.location + '" />');</script>
      <link rel="stylesheet" href="style.css">
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.js"></script>
      <script src="app.js"></script>
      </head>
      <body ng-controller="MainCtrl">
      <div ng-form="myForm" >
      <input ng-model="filename" valid-file required type="file"/>
      <button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary"><i class="icon-white icon-ok"></i>&nbsp;Ok</button>
      <div >
      <textarea name="observations" rows="3" cols="50" ng-model="observations"></textarea>
      </div>
      <p>
      Input is valid: {{myForm.$valid}} Input is invalid: {{myForm.$invalid}}
      <br>Selected file: {{filename}}
      <br>Area is valid: {{myForm.observations.$valid}} Area is invalid: {{myForm.observations.$invalid}}
      </p>
      </div>
      </body>
      </html>


      there's a working plnkr of what I just said:
      http://plnkr.co/edit/k3KZpdX5q3pelWN21NVp?p=preview







      javascript angularjs html5






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 20 at 6:39

























      asked Nov 20 at 1:06









      gerard

      3418




      3418
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote













          A quick hack would be to just take the text-area out of the ng-form like this -



          <div ng-form="myForm">
          <input id="userUpload" ng-model="filename" archivo-valido
          name="userUpload" required type="file"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
          </div>
          <button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary">
          <i class="icon-white icon-ok"></i>&nbsp;Ok
          </button>


          Problem is the Form is invalid in the beginning but you just force the value to true on change. Once you write something in the textarea, the Form reverts back to its original false value. I don't understand the code in your directive -




          ERRONEOUS



           scope.$apply(function(){
          if(true){ // will always evaluate to true. Why the else part then?
          ctrl.$valid=true;
          ctrl.$invalid=false;
          }else{
          ctrl.$valid=false;
          }
          });



          A better approach would be to write Custom Validators on each of your ngModels like this -



          app.directive('archivoValido', function() {
          return {
          require: 'ngModel',
          link: function(scope, elm, attrs, ctrl) {
          ctrl.$validators.archivoValido = function(modelValue, viewValue) {
          if (ctrl.$isEmpty(modelValue)) {
          // consider empty models to be valid
          return true;
          }
          // your custom validation here
          ...
          // it is invalid
          return false;
          };
          }
          };
          });





          share|improve this answer























          • Hi, I just modified code so the piece of code you said you "don't understand" it's clearer(it is meant to make the input always valid so we can see how the textarea it's what makes the program fail) also I changed the html code so I can see form.textArea.$valid and form.textArea.$invalid but doesn't show as you said, textArea is always $valid=true and $invalid=false.
            – gerard
            Nov 20 at 6:58












          • @gerard Thanks for making the answer clearer. Regarding your doubt, it's not the form.textArea.$valid that changes, but form.$valid that reverts back to its original false value when the textArea is changed.
            – slntRohit
            Nov 24 at 0:22











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384807%2fangularjs-directive-for-input-type-file-validation%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote













          A quick hack would be to just take the text-area out of the ng-form like this -



          <div ng-form="myForm">
          <input id="userUpload" ng-model="filename" archivo-valido
          name="userUpload" required type="file"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
          </div>
          <button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary">
          <i class="icon-white icon-ok"></i>&nbsp;Ok
          </button>


          Problem is the Form is invalid in the beginning but you just force the value to true on change. Once you write something in the textarea, the Form reverts back to its original false value. I don't understand the code in your directive -




          ERRONEOUS



           scope.$apply(function(){
          if(true){ // will always evaluate to true. Why the else part then?
          ctrl.$valid=true;
          ctrl.$invalid=false;
          }else{
          ctrl.$valid=false;
          }
          });



          A better approach would be to write Custom Validators on each of your ngModels like this -



          app.directive('archivoValido', function() {
          return {
          require: 'ngModel',
          link: function(scope, elm, attrs, ctrl) {
          ctrl.$validators.archivoValido = function(modelValue, viewValue) {
          if (ctrl.$isEmpty(modelValue)) {
          // consider empty models to be valid
          return true;
          }
          // your custom validation here
          ...
          // it is invalid
          return false;
          };
          }
          };
          });





          share|improve this answer























          • Hi, I just modified code so the piece of code you said you "don't understand" it's clearer(it is meant to make the input always valid so we can see how the textarea it's what makes the program fail) also I changed the html code so I can see form.textArea.$valid and form.textArea.$invalid but doesn't show as you said, textArea is always $valid=true and $invalid=false.
            – gerard
            Nov 20 at 6:58












          • @gerard Thanks for making the answer clearer. Regarding your doubt, it's not the form.textArea.$valid that changes, but form.$valid that reverts back to its original false value when the textArea is changed.
            – slntRohit
            Nov 24 at 0:22















          up vote
          1
          down vote













          A quick hack would be to just take the text-area out of the ng-form like this -



          <div ng-form="myForm">
          <input id="userUpload" ng-model="filename" archivo-valido
          name="userUpload" required type="file"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
          </div>
          <button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary">
          <i class="icon-white icon-ok"></i>&nbsp;Ok
          </button>


          Problem is the Form is invalid in the beginning but you just force the value to true on change. Once you write something in the textarea, the Form reverts back to its original false value. I don't understand the code in your directive -




          ERRONEOUS



           scope.$apply(function(){
          if(true){ // will always evaluate to true. Why the else part then?
          ctrl.$valid=true;
          ctrl.$invalid=false;
          }else{
          ctrl.$valid=false;
          }
          });



          A better approach would be to write Custom Validators on each of your ngModels like this -



          app.directive('archivoValido', function() {
          return {
          require: 'ngModel',
          link: function(scope, elm, attrs, ctrl) {
          ctrl.$validators.archivoValido = function(modelValue, viewValue) {
          if (ctrl.$isEmpty(modelValue)) {
          // consider empty models to be valid
          return true;
          }
          // your custom validation here
          ...
          // it is invalid
          return false;
          };
          }
          };
          });





          share|improve this answer























          • Hi, I just modified code so the piece of code you said you "don't understand" it's clearer(it is meant to make the input always valid so we can see how the textarea it's what makes the program fail) also I changed the html code so I can see form.textArea.$valid and form.textArea.$invalid but doesn't show as you said, textArea is always $valid=true and $invalid=false.
            – gerard
            Nov 20 at 6:58












          • @gerard Thanks for making the answer clearer. Regarding your doubt, it's not the form.textArea.$valid that changes, but form.$valid that reverts back to its original false value when the textArea is changed.
            – slntRohit
            Nov 24 at 0:22













          up vote
          1
          down vote










          up vote
          1
          down vote









          A quick hack would be to just take the text-area out of the ng-form like this -



          <div ng-form="myForm">
          <input id="userUpload" ng-model="filename" archivo-valido
          name="userUpload" required type="file"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
          </div>
          <button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary">
          <i class="icon-white icon-ok"></i>&nbsp;Ok
          </button>


          Problem is the Form is invalid in the beginning but you just force the value to true on change. Once you write something in the textarea, the Form reverts back to its original false value. I don't understand the code in your directive -




          ERRONEOUS



           scope.$apply(function(){
          if(true){ // will always evaluate to true. Why the else part then?
          ctrl.$valid=true;
          ctrl.$invalid=false;
          }else{
          ctrl.$valid=false;
          }
          });



          A better approach would be to write Custom Validators on each of your ngModels like this -



          app.directive('archivoValido', function() {
          return {
          require: 'ngModel',
          link: function(scope, elm, attrs, ctrl) {
          ctrl.$validators.archivoValido = function(modelValue, viewValue) {
          if (ctrl.$isEmpty(modelValue)) {
          // consider empty models to be valid
          return true;
          }
          // your custom validation here
          ...
          // it is invalid
          return false;
          };
          }
          };
          });





          share|improve this answer














          A quick hack would be to just take the text-area out of the ng-form like this -



          <div ng-form="myForm">
          <input id="userUpload" ng-model="filename" archivo-valido
          name="userUpload" required type="file"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />
          </div>
          <button ng-disabled="myForm.$invalid" type="submit" class="btn btn-primary">
          <i class="icon-white icon-ok"></i>&nbsp;Ok
          </button>


          Problem is the Form is invalid in the beginning but you just force the value to true on change. Once you write something in the textarea, the Form reverts back to its original false value. I don't understand the code in your directive -




          ERRONEOUS



           scope.$apply(function(){
          if(true){ // will always evaluate to true. Why the else part then?
          ctrl.$valid=true;
          ctrl.$invalid=false;
          }else{
          ctrl.$valid=false;
          }
          });



          A better approach would be to write Custom Validators on each of your ngModels like this -



          app.directive('archivoValido', function() {
          return {
          require: 'ngModel',
          link: function(scope, elm, attrs, ctrl) {
          ctrl.$validators.archivoValido = function(modelValue, viewValue) {
          if (ctrl.$isEmpty(modelValue)) {
          // consider empty models to be valid
          return true;
          }
          // your custom validation here
          ...
          // it is invalid
          return false;
          };
          }
          };
          });






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 20 at 5:25









          georgeawg

          32.2k104866




          32.2k104866










          answered Nov 20 at 2:08









          slntRohit

          186




          186












          • Hi, I just modified code so the piece of code you said you "don't understand" it's clearer(it is meant to make the input always valid so we can see how the textarea it's what makes the program fail) also I changed the html code so I can see form.textArea.$valid and form.textArea.$invalid but doesn't show as you said, textArea is always $valid=true and $invalid=false.
            – gerard
            Nov 20 at 6:58












          • @gerard Thanks for making the answer clearer. Regarding your doubt, it's not the form.textArea.$valid that changes, but form.$valid that reverts back to its original false value when the textArea is changed.
            – slntRohit
            Nov 24 at 0:22


















          • Hi, I just modified code so the piece of code you said you "don't understand" it's clearer(it is meant to make the input always valid so we can see how the textarea it's what makes the program fail) also I changed the html code so I can see form.textArea.$valid and form.textArea.$invalid but doesn't show as you said, textArea is always $valid=true and $invalid=false.
            – gerard
            Nov 20 at 6:58












          • @gerard Thanks for making the answer clearer. Regarding your doubt, it's not the form.textArea.$valid that changes, but form.$valid that reverts back to its original false value when the textArea is changed.
            – slntRohit
            Nov 24 at 0:22
















          Hi, I just modified code so the piece of code you said you "don't understand" it's clearer(it is meant to make the input always valid so we can see how the textarea it's what makes the program fail) also I changed the html code so I can see form.textArea.$valid and form.textArea.$invalid but doesn't show as you said, textArea is always $valid=true and $invalid=false.
          – gerard
          Nov 20 at 6:58






          Hi, I just modified code so the piece of code you said you "don't understand" it's clearer(it is meant to make the input always valid so we can see how the textarea it's what makes the program fail) also I changed the html code so I can see form.textArea.$valid and form.textArea.$invalid but doesn't show as you said, textArea is always $valid=true and $invalid=false.
          – gerard
          Nov 20 at 6:58














          @gerard Thanks for making the answer clearer. Regarding your doubt, it's not the form.textArea.$valid that changes, but form.$valid that reverts back to its original false value when the textArea is changed.
          – slntRohit
          Nov 24 at 0:22




          @gerard Thanks for making the answer clearer. Regarding your doubt, it's not the form.textArea.$valid that changes, but form.$valid that reverts back to its original false value when the textArea is changed.
          – slntRohit
          Nov 24 at 0:22


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384807%2fangularjs-directive-for-input-type-file-validation%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          Refactoring coordinates for Minecraft Pi buildings written in Python