AngularJS: Prevent hidden form fields being validated

前端 未结 3 1197
Happy的楠姐
Happy的楠姐 2021-01-31 02:08

What is the best way of preventing hidden form fields being validated in AngularJS?

相关标签:
3条回答
  • 2021-01-31 02:20

    You may also completely add or remove it from the DOM/form by using ng-if instead of ng-show.

    <div ng-show="maritalStatus === 'M'">
        Number of children: <input type="number" ng-model="children"  ng-required="maritalStatus == 'M'">
    </div>
    

    to this

    <div ng-if="maritalStatus === 'M'">
        Number of children: <input type="number" ng-model="children"  ng-required="true">
    </div>
    
    0 讨论(0)
  • 2021-01-31 02:28

    You can remove required attribute by using directives:

    <div ng-app="myApp">   
     <input type="backbutton" id="firstName" name="firstName" type="text"  required/>
    

    var app = angular.module('myApp',[]);
    
    app.directive('input',function($compile){
      return {
        restrict:'E',
        compile:function($tElement,$tAttrs){
            console.log("hi there");
          var el = $tElement[0];
          if(el.getAttribute('type')){
            el.removeAttribute('type');
            el.setAttribute($tAttrs.type,'');
            return function(scope){
              $compile(el)(scope);
            }
          }
    
        }  
      }
    });
    
    
    app.directive('remove',function($compile){
      return {
        restrict: 'A',
        replace:true,
        template:'',
          link: function (scope, element, attrs) {
              element.removeAttr('required');
          }
      }
    });
    

    See Fidlle here

    Before:

    <input id="firstName" name="firstName" required="" remove="" class="ng-scope">
    

    After:

    <input id="firstName" name="firstName" remove="" class="ng-scope">
    
    0 讨论(0)
  • 2021-01-31 02:35

    I initially missed the built-in ngRequired directive. There is a required tag as well, which confused me.

    Now, we can use the same logic (which we used to hide the element) to set the ngRequired false.

    Here is an example practical usecase: I want to ask married people the number of children they have, but, if they are not married, simply hide the field about children.

    <form ng-app name="form">
    
        Marital status:
        <select  ng-model="maritalStatus" required>
            <option value="">Select...</option>
            <option value="M">Married</option>
            <option value="UM">Unmarried</option>
        </select>
    
        <div ng-show="maritalStatus == 'M'">
            Number of children: <input type="number" ng-model="children"  ng-required="maritalStatus == 'M'">
        </div>
    
        (for testing) Is this form correctly filled? {{form.$valid}}
    
    </form>
    
    0 讨论(0)
提交回复
热议问题