仅在提交或用户输入时验证表单字段

Eri*_*ner 56 angularjs

我有使用的表单字段required.问题是,在呈现表单时会立即显示错误.我希望它仅在用户实际输入文本字段或提交后显示.

我该如何实现呢?

Ste*_*wie 96

$dirty仅在用户与输入交互后才使用flag显示错误:

<div>
  <input type="email" name="email" ng-model="user.email" required />
  <span ng-show="form.email.$dirty && form.email.$error.required">Email is required</span>
</div>
Run Code Online (Sandbox Code Playgroud)

如果只想在用户提交表单后触发错误,则可以使用单独的标志变量,如下所示:

<form ng-submit="submit()" name="form" ng-controller="MyCtrl">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="(form.email.$dirty || submitted) && form.email.$error.required">
      Email is required
    </span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>
Run Code Online (Sandbox Code Playgroud)
function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  } 
};
Run Code Online (Sandbox Code Playgroud)

然后,如果所有JS内部ng-show表达式对您来说太过分了,您可以将它抽象为一个单独的方法:

function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  }

  $scope.hasError = function(field, validation){
    if(validation){
      return ($scope.form[field].$dirty && $scope.form[field].$error[validation]) || ($scope.submitted && $scope.form[field].$error[validation]);
    }
    return ($scope.form[field].$dirty && $scope.form[field].$invalid) || ($scope.submitted && $scope.form[field].$invalid);
  };

};
Run Code Online (Sandbox Code Playgroud)
<form ng-submit="submit()" name="form">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="hasError('email', 'required')">required</span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>
Run Code Online (Sandbox Code Playgroud)


Nir*_*dhi 5

如果要在提交表单时显示错误消息,则可以使用condition form.$submitted来检查是否尝试提交表单。检查以下示例。

<form name="myForm" novalidate ng-submit="myForm.$valid && createUser()">
  <input type="text" name="name" ng-model="user.name" placeholder="Enter name of user" required>
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user name.</div>
  </div>

  <input type="text" name="address" ng-model="user.address" placeholder="Enter Address" required ng-maxlength="30">
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user address.</div>
    <div ng-message="maxlength">Should be less than 30 chars</div>
  </div>

  <button type="submit">
    Create user
  </button>
</form>
Run Code Online (Sandbox Code Playgroud)