2017-02-04 188 views
1

我想創建一個表達式,以便輸入字符串不能包含正斜槓,逗號或點。正則表達式匹配[/,。] ng模式

<form name="myForm"> 
    <div class="col-sm-4"> 
     <input class="form-control" 
     type="text" 
     data-ng-model="model_name" 
     name="modelName" 
     ng-pattern="/^[\/,.]/" required> 
     <div ng-messages="myForm.$submitted && myForm.modelName.$error" role="alert"> 
     <div class="alert alert-danger" ng-message="pattern">Special characters [/ , .] are not allowed.</div> 
     <div class="alert alert-danger" ng-message="required">This field is required.</div> 
     </div> 
    </div> 
</form> 

正則表達式/^[\/,.]/適當的所有字符匹配的方括號,但問題是,它沒有讓我輸入普通字符串如ABC或abc_def或其他任何字符串。我對正則表達式沒有深刻的瞭解,我也不知道如何解決這個問題。請幫忙。

回答

2

regex是錯誤的,^必須是內[]爲了匹配除了/.,所有字符放在一個[^/.,],正則表達式中使用^當塊[]內將匹配任何東西,但什麼是[]內。

enter image description here

當測試正則表達式,這個網站是有用的:http://www.regexpal.com/

+0

您的解決方案工作。我在方括號之後使用了+,並刪除了g。我在這裏測試了這個模式[https://docs.angularjs.org/api/ng/directive/ngPattern]我不知道爲什麼它不適合我。我還將'myForm.modelName。$ error'更改爲'myForm.modelName。$ valid'。 – AMahajan

+0

'ng-pattern =「/[^\/,.]+/」'不能工作,所以我創建了'$ scope.regex =「[^ \/,.] +」'並寫了'ng-pattern =「正則表達式「,它的工作。你有什麼想法嗎? – AMahajan

+0

我不熟悉角度,對不起。可能是你需要指定該模式將與'ng-pattern =「regex」' – elbaulp