2017-02-04 197 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