angularjs Angular 限制不允许文本字段中有空格

mspsb9vt  于 8个月前  发布在  Angular
关注(0)|答案(9)|浏览(100)

我不希望用户在文本字段中输入空格。我不希望它提交验证,而是-一个空间将不会出现在文本字段,当他们点击它。

fkaflof6

fkaflof61#

选择的答案可以说不是很unobtrusive。如果你需要在多个地方使用它,你最终会得到重复的代码。
我更喜欢使用以下指令来防止输入空格。

app.directive('disallowSpaces', function() {
  return {
    restrict: 'A',

    link: function($scope, $element) {
      $element.bind('input', function() {
        $(this).val($(this).val().replace(/ /g, ''));
      });
    }
  };
});

这个指令可以这样调用:

<input type="text" disallow-spaces>
vc9ivgsu

vc9ivgsu2#

<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">

这里添加ng-trim=“false”属性来禁用输入的修剪是很重要的。

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, '');
              }
          });
        }
    };
  });
yzxexxkh

yzxexxkh3#

如果你想实现它,而不写指令,
ng-keydown="$event.keyCode != 32 ? $event:$event.preventDefault()"

disho6za

disho6za4#

杰森写的指令对我不起作用。我不得不将return false改为:e.preventDefault()如下所示:

app.directive('disallowSpaces', function() {
    return {
        restrict: 'A',

        link: function($scope, $element) {
            $element.bind('keydown', function(e) {
                if (e.which === 32) {
                    e.preventDefault();
                }
            });
        }
    }
});
t5zmwmid

t5zmwmid5#

这可以防止输入任何特殊字符,包括空格:

app.directive('noSpecialChar', function() {
return {
    require: 'ngModel',
    restrict: 'A',
    link: function(scope, element, attrs, modelCtrl) {
        modelCtrl.$parsers.push(function(inputValue) {
            if (inputValue == null)
                return ''
            let cleanInputValue = inputValue.replace(/[^\w]|_/gi, '');
            if (cleanInputValue != inputValue) {
                modelCtrl.$setViewValue(cleanInputValue);
                modelCtrl.$render();
            }
            return cleanInputValue;
        });
    }
}
});
hec6srdp

hec6srdp6#

不使用jquery

angular.module('app').directive('disallowSpaces', function () {
  return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
      maxvalue: '=',
    },
    link: function ($scope, $element, attr, ngModelCtrl) {
      $element.bind('keydown', function () {
        function transformer(text) {
          if (text) {
            var transformedInput = text.replace(/ /g, '');
            ngModelCtrl.$setViewValue(transformedInput);
            ngModelCtrl.$render();
            return transformedInput;
          }
          return undefined;
        }
        ngModelCtrl.$parsers.push(transformer);
      });
    },
  };
});

// use disallow-spaces

<input type="text" ng-model="name" disallow-spaces />
yiytaume

yiytaume7#

您可以在不编写指令的情况下实现这一点。

<input ng-model="myModel" ng-keydown="$event.keyCode != 32 ? $event:$event.preventDefault()">
vd2z7a6w

vd2z7a6w8#

Angular 9不支持Keycode。
下面的代码可以帮助你。
public void run(){

if (event.code === 'Space') {
        event.preventDefault();
    }
}
dauxcl2d

dauxcl2d9#

您可以为此定义一个指令。使用Angular v16测试

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

@Directive({
    selector: '[appInputTrim]'
})
/**
 * This directive is used to trim the input value.
 * @author Hakkı Konu
 */
export class InputTrimDirective {
    constructor(private el: ElementRef) {
    }

    @HostListener('input', ['$event.target.value'])
    trim(value: string) {
        this.el.nativeElement.value = value.trim();
        console.log('value', value);
    }
}

使用

<input appInputTrim .... />

相关问题