【问题标题】:Validate form with all fields in AngularJs使用 AngularJs 中的所有字段验证表单
【发布时间】:2016-10-31 18:38:21
【问题描述】:

验证 AngularJS 中所有字段的最佳方法是什么。

我有一个包含 7 个字段的表单,所有字段都是必填的,如果任何字段无效,我想在边框中显示错误消息或更改。

我使用以下方法。请告诉我这是正确的方法。如果明天我有 100 个字段怎么办。

if(!($scope.signInForm.email.$valid)){
    $scope.emailError = true;
}
else {
    $scope.emailError = false;
}
if(!($scope.signInForm.password.$valid)){
    $scope.passwordError = true;
}
else {
    $scope.passwordError = false;
}

【问题讨论】:

标签: angularjs validation


【解决方案1】:

您可以在模板中处理此问题,请参阅文档中的更多信息: https://docs.angularjs.org/guide/forms

来自文档

<form name="myForm" class="css-form" novalidate>
  <div>
    <input type="email" name="input" ng-model="email.text" required>

    <span class="error" ng-show="myForm.input.$error.required">
        Required!
    </span>
    <span class="error" ng-show="myForm.input.$error.email">
        Not valid email!
    </span>
  </div>
  ...

  <!-- If you want to disable the button until all fields are filled in correctly.-->
  <button class="btn btn-default" ng-disabled="myForm.$invalid">Login</button>
</form>

正如 Alex 所说,查看 ngMessages 也是一个好主意,您可以在这里找到有用的信息:http://blog.thoughtram.io/2015/06/06/ng-messages-revisited.html

【讨论】:

    【解决方案2】:
      newuser = new FormGroup({
        firstname: new FormControl(''),
        lastname: new FormControl(''),
        usertype: new FormControl(''),
        phoneno: new FormControl(''),
        city: new FormControl(''),
        zip: new FormControl(''),
        agree:new FormControl('')
      });
    
    
    
    
      submitform(){
        if(this.newuser.status=="VALID"){
            console.log(this.newuser.value);   
        }   
      }
    

    【讨论】:

      猜你喜欢
      • 2014-02-24
      • 1970-01-01
      • 2014-02-22
      • 2014-08-02
      • 2021-11-08
      • 2017-03-17
      • 2016-01-01
      • 2019-12-10
      • 1970-01-01
      相关资源
      最近更新 更多