-1

Need to show error message whenever i enter space in password input field using ng-pattern.

Santhoshkumar
  • 780
  • 1
  • 16
  • 36
  • Possible duplicate of [Regular expression for not allowing spaces in the input field](https://stackoverflow.com/questions/16334765/regular-expression-for-not-allowing-spaces-in-the-input-field) – Sajal Jul 05 '17 at 06:45
  • What have you tried? You just have to use an `ng-pattern` like `ng-pattern="/^[a-zA-Z\d\-\_]+$/"` and set `ng-trim="false"`. See [this answer](https://stackoverflow.com/a/31417133/3153169) – devqon Jul 05 '17 at 06:46
  • Keep checking on change `pass.indexOf('_')` its easy to check and – Jayant Patil Jul 05 '17 at 06:47

2 Answers2

2

Use of regEx - /^\S*$/ does not allow space anywhere in the string.

<form name="myForm">
   <input type='password' name="passInpt" ng-model='pass' data-ng-pattern="/^\S*$/">
   <div data-ng-show="myForm.passInpt.$error.pattern" >White Space not allowed</div>
</form>

DEMO:

var app = angular.module("app", []);
app.controller("ctrl", function($scope) {});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="app" ng-controller="ctrl">
  <form name="myForm">
    <input type='password' name="passInpt" ng-model='pass' data-ng-pattern="/^\S*$/">
    <div data-ng-show="myForm.passInpt.$error.pattern">White Space not allowed</div>
  </form>
</body>
Sajal
  • 4,359
  • 1
  • 19
  • 39
alfishan aqeel
  • 220
  • 2
  • 5
0

Here is the link Jsfiddle demo

You can check for indexof or you can use regX for it.

HTML

<div ng-app="myApp">
  <div ng-controller="ctrl">

    <form>
      <span>{{error}}</span>
      <input type='password' ng-model='pass' ng-change='check()'>
    </form>
  </div>
</div>

**JS **

  var app = angular.module('myApp', []);

  app.controller('ctrl', function($scope) {
    $scope.error = '';
    $scope.check = function() {
      $scope.pass.indexOf(' ') > -1 ? ($scope.error = 'Invalid') : ($scope.error = '');
    }
  })

Hope this will help you

updated for space

Jayant Patil
  • 1,537
  • 2
  • 11
  • 18