角度限制,不允许在文本字段中使用空格 [英] angular restriction to not allow spaces in text field

查看:78
本文介绍了角度限制,不允许在文本字段中使用空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不希望用户在文本字段中输入空格.我不希望在提交验证时使用它,而是-单击它们时在文本字段上不会显示空格.

I do not want a user to enter spaces in a text field. I don't want it on submit validation but rather - a space will not show up on the text field when they click it.

推荐答案

<input ng-model="field" ng-trim="false" ng-change="field = field.split(' ').join('')" type="text">

更新: 为了提高代码质量,您可以创建自定义指令.但是请不要忘记,您的指令不仅应防止键盘输入,而且应防止粘贴.

Update: To improve code quality you can create custom directive instead. But don't forget that your directive should prevent input not only from keyboard, but also from pasting.

<input type="text" ng-trim="false" ng-model="myValue" restrict-field="myValue">

在此处添加ng-trim ="false"属性以禁用输入修整很重要.

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

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

这篇关于角度限制,不允许在文本字段中使用空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆