簡體   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