Home > Enterprise >  not allow space and symbol in input Angular
not allow space and symbol in input Angular

Time:12-22

i am having a problem that there is an input that does not accept spaces and special characters, i have custom a directives, it works fine on pc but on mobile it doesn't, below is my code:

in directive:

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[pre-space]'
})

export class PreventPasteAndSpaceDirective {

  private regex: RegExp = new RegExp(/[0-9a-zA-Z]$/g);
  private specialKeys: Array<string> = ['Backspace','ArrowLeft', 'ArrowRight', 'Delete'];

  constructor(private el: ElementRef) {
  }
  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
    const current: string = this.el.nativeElement.value;
    const next: string = current.concat(event.key);
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }

  @HostListener('paste', ['$event'])
  blockPaste(event: KeyboardEvent) {
    event.preventDefault();
  }
}

in HTML

<div>
  <label for="">Test</label>
  <input type="text" name="test"  pre-space>
</div>

CodePudding user response:

Look like you hostlistener for touch.

You can try the following and add listener for it

@HostListener('touchstart', ['$event'])
@HostListener('touchend', ['$event'])
@HostListener('touchcancel', ['$event'])

Using_Touch_Events

CodePudding user response:

Here is important to add ng-trim="false" attribute to disable trimming of an input.

<input ng-model="field" ng-trim="false" ng-change="field = field.split(' ').join('')" type="text">
<input type="text" ng-trim="false" ng-model="myValue" restrict-field="myValue">
angular
  .module('app')
  .directive('restrictField', function () {
    return {
        restrict: 'AE',
        scope: {
            restrictField: '='
        },
        link: function (scope) {
          // this will match spaces, tabs, line feeds etc
          // you can change this regex as you want
          var regex = /\s/g;

          scope.$watch('restrictField', function (newValue, oldValue) {
              if (newValue != oldValue && regex.test(newValue)) {
                scope.restrictField = newValue.replace(regex, '');
              }
          });
        }
    };
  });
  • Related