首页 文章

使用ng-pattern进行Angularjs表单验证

提问于
浏览
1

我正在使用ng-pattern来验证字段,并在使用ng-messages与特定模式不匹配时显示消息 . 我遇到的问题是表单有一个下一个按钮,正在禁用/启用ng-diabled“form . $ invalid”,所以当输入无效时,表单无效 .

我想要实现的是当ng-pattern不匹配但不将表单设置为无效时显示带有ng-message的消息 . 本质上,我试图提供一个提示,即用户输入的文本可能无效,同时不阻止提交表单 .

2 回答

  • 1

    根据我的理解,您正在使用ng-disabled这意味着您希望在表单无效时禁用按钮但是对于某些特定条件,您只想显示错误消息但不会使表单无效

    如果是这种情况,只需在控制器中为该ng-model值添加一个观察器,并切换变量以显示或隐藏该错误消息

    $scope.$watch('email', function() {
      if (email == 'abx@xyz.com') {
        flag = true;
      }
      else {
        flag = false;
      }
    })
    

    Note this is for specific case only, Avoid using watchers it slows down your app

  • 0

    我想你想要这样 . 这里,如果十进制值不匹配,则此模式将不允许提交数据 .

    <input class="form-control" type="dacimal" name="percentage" ng-model="percentage" ng-min="0.01" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" step="0.01" required>
    <span class="alert-danger" ng-show="studentForm.$submitted || (studentForm.percentage.$dirty && studentForm.percentage.$invalid)">
      <span ng-show="studentForm.percentage.$error.required">Percentage is required !</span>
      <span ng-show="!studentForm.percentage.$valid">Invalid Percentage !</span>
    </span>
    

相关问题