【问题标题】:how to include qutoes + double quotes in ng-regex?如何在 ng-regex 中包含 qutoes + 双引号?
【发布时间】:2016-05-16 15:00:34
【问题描述】:

我在 android studio 中开发了 phonegap 应用程序。

我有一个必须允许 abc 字符、引号和双引号的输入字段。
想要的html代码:

 <input placeholder="last name" type="text" ng-model="currentUser.LastName"
                       ng-pattern='/^([A-Za-z\"\' ]){1,45}$/'
                       required
                       class="form-control"/>

但我有一个问题 - 正则表达式中的引号关闭了整个正则表达式。
我能做什么:

ng-pattern='/^([A-Za-z\" ]){1,45}$/'

ng-pattern="/^([A-Za-z\' ]){1,45}$/"

但我也找不到包含引号和双引号的方法。

我试过了:

范围内:

$scope.regex=/^([A-Za-z\"\' ]){1,45}$/;

在html页面中:

<input placeholder="last name" type="text" ng-model="currentUser.LastName" name="userLastName1"
                       ng-pattern='{{regex}}'
                       required
                       class="form-control"/>

也没有用(我的编辑器是android studio,也许其他编辑器更好?)。

有没有办法在一个正则表达式中同时包含引号和双引号?

【问题讨论】:

  • According to the documentation 你不需要插入范围变量。您应该能够将它作为$scope.regex=/^([A-Za-z\"\' ]){1,45}$/; 放入您的控制器中,然后在您的模板中使用它作为ng-pattern='regex'
  • 我刚刚编辑过,有问题,实际代码是对的但它不起作用。
  • it did not work 是什么意思?

标签: javascript android angularjs regex


【解决方案1】:

您可以对这些实体使用十六进制值,\x22 用于 "\x27 用于 '

$scope.regex= "/^[A-Za-z\x22\x27 ]{1,45}$/";

而且你不需要外括号。

你可以测试一下here

或者这里是一个 sn-p,显示它在 ng-pattern 属性中工作:

function formCtrl($scope){
  $scope.onSubmit = function(){
    alert("form submitted");
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="formCtrl">
  <form name="myForm" ng-submit="onSubmit()">
    <input type="text" name="field" ng-model="formCtrl" ng-pattern="/^[A-Za-z\x22\x27 ]{1,45}$/" required placeholder="last name">
    <span ng-show="myForm.field.$error.pattern">Not valid!</span>
    <span ng-show="myForm.field.$error.required">This field is required!</span>
    <input type="submit" value="submit"/>
  </form>
</div>

【讨论】:

  • 很高兴它对你有用。请考虑接受答案。顺便说一句,ng-pattern="/^[A-Za-z'\x22 ]{1,45}$/" 也应该可以工作(无需“混淆”单个撇号)。
猜你喜欢
  • 2017-11-07
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 2011-12-09
  • 2015-09-06
  • 2012-04-06
  • 1970-01-01
相关资源
最近更新 更多