繁体   English   中英

AngularJS - 正则表达式不应以空格开头和结尾,不应包含双引号 (")

[英]AngularJS - regular expression which should not start & end with space and should not consist double quotation (")

我写了 ng-pattern 不以空格开头和结尾。 并试图匹配 $watch 中的双引号。

但它不起作用。 ng-pattern 也不起作用

我的 ng 模式是:

<input type="text" class="form-control" ng-model="wifiResult.ssid" 
     name="ssid"
     ng-class="{'inputError' : errorMsg}"
     ng-minlength="1"
     ng-maxlength="32"
     ng-pattern="/^[^\s]+(\s+[^\s]+)*$/"
     required >

JS 中的 $watch 是:

$scope.$watch('wifiResult.ssid', function(scope){
        var regexToRestrict = /^["]+$/;

        if(scope){
            var pressChar       = scope.slice(-1);
            if(pressChar.match(regexToRestrict)){
                scope   = scope.slice(0,-1); // try to replace " to blank
            }
            else{
                console.log('not matched');
            }
        }       
        else{
            console.log('no scope');
        }
    });

有没有其他方法可以做到这一点?

提前致谢 !

您可以将正则表达式更改为ng-pattern='/^[^\\\\\\\\./:*?\\"<>|][^\\\\\\\\/:*?\\"<>|]{0,254}$/'在您的 html 中以防止用户在输入和表单中输入 (") 可能会引发错误,指出这是无效输入。

在 angular ng-trim中默认设置为 true,因此在分配给ng-model之前,用户输入周围的任何空格都会被删除。

您不需要观察者,除非并且直到您希望每次用户尝试在输入字段中输入某个值时输入值都为 (") 空闲。每次用户更改某些内容时进行验证是不必要的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM