Get trailing white space from input type password

2020-07-17 16:27发布

问题:

I have an input password field. I want to be able to warn the user that they cannot have any white space in there password. The trouble I'm finding is that I cant pass the trailing white space to the scope in order to detect it and warn the user that they cannot do this.

See my plunkr example: LINK

If you type in the input field the scope will return how many characters the password is and if you add white space at the end of the password the scope will not report the correct string length because it is obviously trimming any trailing white space which means I have no way to identify if the user is entering any spaces or not. So as the user adds trailing spaces the input password field will show that an extra character has been added when the scope is only reporting the length of characters without any trailing spaces.

回答1:

Here's the fixed plunkr solution is upgrade to 1.1.1 of angular to take advantage of ng-trim directive which allows you to turn off the trimming: http://plnkr.co/edit/FLCQY2zuRV1ZMy6WCbs8?p=preview

Upgrade to Angular 1.1.1 or higher (tested, might work in some lower versions) add this directive to your element where you have the ng-model you don't want trimmed.

ng-trim="false"

Here's the full details:

<!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 data-require="angular.js@1.1.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.1/angular.min.js" data-semver="1.1.1"></script>
    <script src="angular_ui.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <form>
      Pass length is {{pass.length}}<br>
      <input type="password" data-ng-model="pass" data-ng-trim="false">
    </form>
  </body>

</html>

And the JS

var app = angular.module('plunker', ['ui.event']);

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