AngularJS ng-pattern函数,带有regEx和日期输入字段

时间:2015-01-23 13:11:40

标签: javascript regex angularjs

我的客户请求将一个唯一的表单验证规则添加到文本输入中,该输出除了4位数字,没有字符。输入应该采用像2015年一样的年份格式。问题是客户不希望用户输入低于当前年份的年份,并且不能超过当年的10年。

所以我创建了一个这样的函数:

$scope.startYearPattern = function() {
      var date = new Date();
      var year = date.getFullYear();
      var regex = /^[0-9]{2}$/;
      if(EditProgCtrl.programDetails.academicYear > year && EditProgCtrl.programDetails.academicYear < year + 10 && regex);
        };

然后在html上我有:

<div class="col-xs-6 form-horizontal program-edit" data-ng-class="{ 'has-error': programEditForm.academicYear.$invalid && programEditForm.academicYear.$touched }">
                    <div class="form-group required">
                        <label for="academicYear" class="col-xs-4 horizontal-left control-label">
                            Start Year
                        </label>
                        <div class="col-xs-6 program-edit">
                            <input type="text" ng-pattern="startYearPattern()" class="form-control input-sm" max="3000" name="academicYear" id="academicYear" data-ng-model="EditProgCtrl.programDetails.academicYear" title="Please enter a valid year" required="required" />
                            <div data-ng-if="programEditForm.academicYear.$touched" data-ng-messages="programEditForm.academicYear.$error">
                                <span class="help-block" data-ng-message="required">required field</span>
                                <span class="help-block" data-ng-message="pattern">Wrong Year Format</span>
                            </div>
                        </div>
                    </div>
                </div>

它虽然没有用,所以我错过了一些东西,只是不知道出了什么问题。

1 个答案:

答案 0 :(得分:0)

ng-pattern通常只接受像ng-pattern =&#34; / ^ [0-9] {4} $ /&#34;我想。我写了一个验证指令

myModule.directive('academicYearValidation', academicYearValidation );
function academicYearValidation() {
    return {
       restrict: 'A',
       require: 'ngModel',
       link: link
    }
   function link (scope, element, attrs, ngModel) {

       function validator(modelValue, viewValue) {
          var value = modelValue || viewValue;
          var date = new Date();
          var year = date.getFullYear();
          var regex = /^[0-9]{4}$/;

          if(regex.test(value) && value > year && value < year + 10){
              return true;
          }else{
              return false;
          }
        }
        ngModel.$validators.academicyearvalidation = validator;
    }
};

(ngModel。$ validators是1.3之前的新角色,你必须使用ngModel。$ parsers和ngModel。$ formatters)

我让你成了一名羽毛http://plnkr.co/edit/jtCqB0zZhelQCXF6iiK6?p=preview