aman
aman

Reputation: 6262

AngularJs textbox validation, restricting characters with regex negative lookahead

Using angular js here:

I have a textbox where I want to apply certain regex and prevent the user with certain characters. Here is what I want:

Below is code what I have:

TextBox:

 <input type="text" name="uname" ng-model="uname" required class="form-
  control input-medium" placeholder="Enter  name..." maxlength="20" restrict-
  field="alpha-numeric" ng-trim="false" />

Directive:

.directive("restrictField", function() {
return {
  require: "ngModel",
  restrict: "A",
  link: function(scope, element, attrs, ctrl) {
    var regReplace,
      preset = {
        "alphanumeric-spl": "\\w_./s/g",
        "alphanumeric-underscore": "\\w_",
        "numeric": "0-9",
        "alpha-numeric": "\\w"           
      },
      filter = preset[attrs.restrictField] || attrs.restrictField;

    ctrl.$parsers.push(function(inputValue) {
      regReplace = new RegExp('[^' + filter + ']', 'ig');

      if (inputValue == undefined) return "";
      cleanInputValue = inputValue.replace(regReplace, "");
      if (cleanInputValue != inputValue) {
        ctrl.$setViewValue(cleanInputValue);
        ctrl.$render();
      }
      return cleanInputValue;
    });
  }
   };
  });

While the above works for the simple patterns that I have used in my directives but does not work for the pattern which I have described above. From my other post I have got the pattern to use for regex negative lookahead as below:

^(?!_)(?!.*_$)[a-zA-Z0-9_]+$

But this does not work if I try to include it in my directive.

Here is my sample Codepen that I have created:https://codepen.io/anon/pen/LJBbQd

How can I apply the above regex. If not this, is there a workaround or any other approach to restrict my textbox with this regex.

Thanks

Upvotes: 0

Views: 129

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627083

I suggest to allow a _ at the end, and use an HTML5 pattern attribute with a regex that requires the last char to be any char but a _ with pattern=".*[^_]". If you need to allow an empty string, use pattern="(?:.*[^_])?".

var app = angular
  .module("myApp", ["ui.bootstrap"])
  .directive("restrictField", function() {
    return {
      require: "ngModel",
      restrict: "A",
      link: function(scope, element, attrs, ctrl) {
        var regReplace,
          preset = {
            'alphanumeric-spl': '[^\\w\\s./]+', // Removes all but alnum, _ . / whitespaces
            'alphanumeric-underscore': '^_+|_+(?=_)|\\W+', // Removes all _ at start and all _ before a _ and all but alnum and _
            'numeric': '[^0-9]+', // Removes all but digits
            'alpha-numeric': '[\\W_]+' // Removes all but alnum
          },
          filter = preset[attrs.restrictField] || attrs.restrictField;

        ctrl.$parsers.push(function(inputValue) {
          console.log(filter);
          regReplace = RegExp(filter, 'ig');

          if (inputValue == undefined) return "";
          cleanInputValue = inputValue.replace(regReplace, "");
          if (cleanInputValue != inputValue) {
            ctrl.$setViewValue(cleanInputValue);
            ctrl.$render();
          }
          return cleanInputValue;
        });
      }
    };
  });

// Define the `appController` controller on the `ReportsMockUpsApp` module
app.controller("ctrl", function($scope) {});
body {
  padding: 10px
}

input:valid {
  color: black;
  border: 5px solid #dadadada;
  border-radius: 7px;
}

input:invalid {
  color: navy;
  outline: .glowing-border:focus;
  border-color: #ff1050;
  box-shadow: 0 0 10px #ff0000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/0.13.4/ui-bootstrap-tpls.min.js"></script>
<script src="https://code.angularjs.org/1.3.4/angular.min.js"></script>
<div class="container" ng-app="myApp">
  <div ng-controller="ctrl">
    <label>Wow</label>
    <input type="text" pattern=".*[^_]" name="uname" ng-model="uname" required class="form-control input-medium" placeholder="Enter  name..." maxlength="20" restrict-field="alphanumeric-underscore" ng-trim="false" />


  </div>
</div>

Upvotes: 0

Related Questions