正则表达式根据条件

时间:2017-05-27 08:32:42

标签: angularjs regex phone-number

我正在尝试编写一个指令,它传递两个字段的ng模型,如移动代码和手机号码。

我正在讨论ngmodels以及我在哪里使用REGEX。

条件是这样的, 如果移动代码是015x-移动数字的总数应严格为12

如果移动代码是01xx或01xxx - 那么总的位数将是11或12。

代码是:

angular.module('Validation').directive('mobileNumberValidator', function () {
var MOBILE_NUMBER_REGX = /^(?:(?=015)[0-9]{12} | [0-9]{11,12} )$/;

return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
        mobilecode: '='
    },

    link: function (scope, element, attrs, ngModel) {
        dovalidation();
        element.bind('blur', function () {
            scope.$apply(dovalidation);
        });

        function dovalidation() {
            ngModel.$validators.InvalidMobileNumber = function (modelValue, viewValue) {

                var value = modelValue || viewValue;
                var regexp = scope.mobilecode + value;
                if (regexp.length !== 0) {
                    return MOBILE_NUMBER_REGX.test(regexp);
                }

            };
        }
    }

};
});

但RegEx无法按预期工作。 :(

2 个答案:

答案 0 :(得分:1)

试试这个正则表达式:

/^((015\d{9})|(01[0-46-9]\d{8,9}))$/

表示:015 + 9个其他数字或01 +不是5 + 8-9个其他数字。

答案 1 :(得分:0)

Rusty的模式可行,但这个模式更好(更快,更短):

Pattern Demo

/^01(?:[0-46-9]\d{8,9}|5\d{9})$/

  • 没有捕获组
  • 合并01 start
  • 首先提出更短的替代模式