2

I have a form which has an input field which is a mandatory field for mobile devices but not for desktop or tablets. If I add a required attribute and hide it using CSS media queries in desktop still the form.$valid is false. Is there a way in angular to ensure the required attribute is checked only in mobile devices like putting a ng-required = "mobileOnly".

Thanks in Advance.

Jyotirmoy Pan
  • 837
  • 2
  • 10
  • 28

3 Answers3

3

Try setting a variable in angular scope to check if it's mobile and then put it into ng-required:

angular.module('app', [])
  .controller('Controller', function($scope) {
    $scope.is_mobile = false;
    if (/Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
        $scope.is_mobile = true;

    }
  })
<!DOCTYPE html>

<head>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body ng-app="app">
  <div ng-controller="Controller">
    <form name="myForm" id="myForm">
      <label>Required Field</label>
      <input type="text" ng-model="first" ng-required="true" /><br>
      <label>Required Field for mobile only</label>
      <input type="text" ng-model="second" ng-required="is_mobile" />
    </form><br>
    <b>Form Valid : </b> {{myForm.$valid}}
  </div>
</body>

</html>
Gaurav Srivastava
  • 3,232
  • 3
  • 16
  • 36
3

Using an ng-if statement on your input element will keep angular from checking for validity when it isn't displayed.

<input ng-if="!isMobile" type="text" ng-model="model" required />
shanzilla
  • 467
  • 4
  • 16
1

Well, not directly, because media queries and CSS in general are not represented in any way in Model-ViewModel two way binding of Angular. You'd need to bridge your media queries to your ViewModel somehow.

Probably the easiest route is exactly what you've proposed. With ng-required="isMobile" you can have the field mandatory only when isMobile scope variable is true.

To actually fill $scope.isMobile you'd need to read the viewport dimensions, something like this:

var width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
$scope.isMobile = width < 767; 
// or whatever your mobile breakpoint value in px is

If you care, you should also listen to window.onresize event to handle resizes and update the $scope.isMobile variable accordingly.

Community
  • 1
  • 1
NOtherDev
  • 9,542
  • 2
  • 36
  • 47