【问题标题】:Validate input field only after clicking save button on angular仅在单击角度上的保存按钮后验证输入字段
【发布时间】:2014-10-14 19:40:39
【问题描述】:

我想验证我输入的必填字段,并在单击表单中的保存按钮(提交)后仅显示错误消息。 在 angularjs 中最好的方法是什么?

谢谢,

【问题讨论】:

标签: javascript html angularjs validation


【解决方案1】:

请查看answer

您可以在该链接中找到示例说明

module = angular.module('app', []);

module.directive('showErrors', function() {
    return {
      restrict: 'A',
      require: '^form',
      link: function (scope, el, attrs, formCtrl) {
        // find the text box element, which has the 'name' attribute
        var inputEl   = el[0].querySelector("[name]");
        // convert the native text box element to an angular element
        var inputNgEl = angular.element(inputEl);
        // get the name on the text box
        var inputName = inputNgEl.attr('name');

        // only apply the has-error class after the user leaves the text box
        inputNgEl.bind('blur', function() {
          el.toggleClass('has-error', formCtrl[inputName].$invalid);
        })
      }
    }
  });

module.controller('NewUserController', function($scope) {
  $scope.save = function() {
    if ($scope.userForm.$valid) {
      alert('User saved');
      $scope.reset();
    } else {
      alert("There are invalid fields");
    }
  };

  $scope.reset = function() {
    $scope.user = { name: '', email: '' };
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多