【问题标题】:Two writing methods from 1 to 12 can be written separately or multiple months, but the middle needs to be separated by a comma and cannot be repeated1到12两种写法可以分开写也可以多月写,但是中间需要用逗号隔开,不能重复
【发布时间】:2026-01-06 14:40:02
【问题描述】:

输入模式的正则校验可以单独写或1-12月1、2、3、5、4写,但不能重复

 <input cdkTrapFocus [cdkTrapFocusAutoCapture]="true" type="address" matInput
         [(ngModel)]="Time.month" name="month" #month=ngModel
          pattern="^([1-9]|1[0-2])$|^(([1-9]|1[0-2])+(,[1-9]|,1[0-2])*)?$|^[*]*$">

我可以验证重复项,但我不知道如何将它们合并到顶部

/\b(\d+)\b.*?,\1\b/.test(event)

【问题讨论】:

标签: javascript


【解决方案1】:

[1-9] 匹配 1、2、3、4、5、6、7、8、9

1[012] 匹配 10、11、12

const regex = new RegExp('^([1-9]|1[012])$');

// true.
console.log(regex.test("1")); // true
console.log(regex.test("2")); // true
console.log(regex.test("3")); // true
console.log(regex.test("4")); // true
console.log(regex.test("5")); // true
console.log(regex.test("6")); // true
console.log(regex.test("7")); // true
console.log(regex.test("8")); // true
console.log(regex.test("9")); // true
console.log(regex.test("10")); // true
console.log(regex.test("11")); // true
console.log(regex.test("12")); // true

// false.
console.log(regex.test("123")); // false
console.log(regex.test("111")); // false
console.log(regex.test("01")); // false
console.log(regex.test("13")); // false

参考How can I use a regular expression to validate month input?

附录

[编辑]

您可以验证表单提交时的输入,如果它具有有效月份并且月份数字不重复。

const hasValidMonths = input => {
    const regex = new RegExp('^([1-9]|1[012])$');

    return input
        .trim()
        .split(",")
        .every(num => regex.test(num.trim()));
};

const hasUniqueMonths = input => {
    const months = input.trim().split(",").map(m => m.trim());
    return (new Set(months)).size === months.length;
};

let input = "1, 2, 3, 4, 5, 6";

// true.
console.log(hasValidMonths(input) && hasUniqueMonths(input)); // true

// false.
input = "1, 2, 3, 4, 123, 3";
console.log(hasValidMonths(input) && hasUniqueMonths(input)); // false

演示

(function(angular) {
  'use strict';
  var app = angular.module('form-example1', []);

  app.directive('valid.months', function() {
    return {
      require: 'ngModel',
      link: function(scope, elm, attrs, ctrl) {
        ctrl.$validators.valid_months = function(modelValue, viewValue) {
          // alert(viewValue)
          if (ctrl.$isEmpty(modelValue)) {
            // consider empty models to be valid
            return true;
          }

          const regex = new RegExp('^([1-9]|1[012])$');

          return viewValue
            .trim()
            .split(',')
            .every((num) => regex.test(num.trim()));
        };
      },
    };
  });

  app.directive('unique.months', function() {
    return {
      require: 'ngModel',
      link: function(scope, elm, attrs, ctrl) {
        ctrl.$validators.unique_months = function(modelValue, viewValue) {
          if (ctrl.$isEmpty(modelValue)) {
            // consider empty models to be valid
            return true;
          }

          const months = viewValue
            .trim()
            .split(',')
            .map((m) => m.trim());
          return new Set(months).size === months.length;
        };
      },
    };
  });
})(window.angular);
<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Example - example-forms-async-validation-production</title>


  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
  <script src="script.js"></script>



</head>

<body ng-app="form-example1">
  <form name="form" class="css-form" novalidate>
    <div>
      <label>
    Months:
    <input type="text" ng-model="size" name="size" valid.months unique.months />{{size}}</label><br />
      <span ng-show="form.size.$error.valid_months">The month(s) list format is invalid!. Allowed digits include: 1,2,3,4,5,6,7,8,9,10,11,12. Correct format: 1, 2, 3, 5</span>
      <br />
      <span ng-show="form.size.$error.unique_months">The month(s) list specified contains duplicates!. Correct format: 1, 2, 3, 5</span>
    </div>

  </form>
</body>

</html>

【讨论】:

  • 需要写1、2、3、4、5,不能重复
  • @123KsL , const regex = new RegExp('^([1-5])$');
  • 我可能需要几个月,所以会有1、2、3、4、5、6,而且不能重复
  • @KsL ,在我更新的答案中查看我的 附录 部分。
  • 谢谢,但我想知道有没有直接满足所有条件的正则表达式