簡體   English   中英

在Angular中顯示表單驗證錯誤的正確方法?

[英]Proper way to display form validation errors in Angular?

如果觸發了驗證錯誤,我將在頁面頂部顯示警報,當錯誤修復后,當前的實現也會隱藏該錯誤。 一切正常,但效率低下,有沒有更好的方法?

HTML:

<div class="alert alert-danger"
  ng-repeat error in advAlerts
  ng-show="error.hasError()">
  {{error.text}}
</div>

JS:

$scope.advAlerts = [
  {
    hasError: checkFooError,
    text: 'Error Foo',
  },
  {
    hasError: checkBarError,
    text: 'Error Bar',
  },
  ...
]   

function checkFooError() {
  //check a list of required attributes to see they're all filled out
  //returns true/false
}

使用此方法,頁面可以響應:單擊提交后,如果缺少任何必需的屬性,則會顯示警報。 填寫所有必需的屬性后,警報立即消失。

但是,由於摘要周期(我認為?),checkFooError函數被稱為“噸”,有沒有更好的方法呢?

-編輯-

標准驗證已經就緒,我忘了提到這些是“高級警報”,因為它們是設計人員想要的額外東西。

好了,您不必為AngularJS中的表單驗證編寫太多代碼。 AngularJS為我們提供了一些可用於檢查表單狀態的屬性。 因此,您可以從各個方面檢查for及其控制器的狀態。

表格狀態:-

$valid :驗證表單是否與html控件中定義的規則匹配

$invalid :根據定義的規則驗證表單是否無效

$pristine :如果用戶未使用HTML控件/標記, $pristine true

$dirty :如果用戶已使用HTML控件/標記, $dirty true

用法示例:-

<div class="form-group" ng-class="{ 'has-error' : yourForm.username.$invalid && !yourForm.username.$pristine }">
    <label>Username</label>
    <input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8" required>
    <p ng-show="yourForm.username.$error.required">Username is short.</p>
    <p ng-show="yourForm.username.$error.minlength">Username is short.</p>
    <p ng-show="yourForm.username.$error.maxlength">Username is long.</p>
</div>

<div class="form-group" ng-class="{ 'has-error' : yourForm.email.$invalid && !yourForm.email.$pristine }">
    <label>Email</label>
    <input type="email" name="email" class="form-control" ng-model="user.email">
    <p ng-show="yourForm.email.$invalid && !yourForm.email.$pristine" >Enter a valid email.</p>
</div>

參考: 表格的Angular文檔

如果要避免在HTML中使用樣板代碼,則可以避免將所有這些ng-show和類似的內容放入表單中,從而將其與驗證機制本身完全分離。

在客戶端執行驗證時,您不必一定要與angular捆綁在一起,可以將angularjs與任何其他JS框架組合在一起,並使它們與requireJS一起作為獨立模塊一起工作。 我一直在使用bootstrapValidator和angular,將它們與requireJS綁定在一起,它的性能很好,在html中為您提供了干凈的代碼,具有完全解耦的模塊,當您使用$ viewContentLoaded加載視圖時,可以附加一個偵聽器,然后使用函數調用在您的表單上啟用驗證,我以示例代碼為例:

  1. 干凈的angularJS形式:

      <form id="myForm" novalidate="novalidate" class="form-horizontal"> <label>name</label> <input type="text" class="form-control" id="name" name="name" ng-model="rec.name" /> <label>description</label> <textarea rows="5" id="description" ng-model="rec.description" name="description"> </textarea> // ... more fields 

在您的控制器代碼中:

controllers.controller('MyCtrl', ['$scope', 'MyService',
  function($scope, MyService) {
    // ... controller code

    // setup validator based on your page form
    $scope.$on('$viewContentLoaded', loadFormValidator);        
  }]);

function loadFormValidator(){
    $('#myForm').bootstrapValidator({
        message: 'The form has invalid inputs',
        fields: {
            name: {
                message: 'The name is not valid',
                validators: {
                    notEmpty: {
                        message: 'The name is required and can\'t be empty'
                    },
                    stringLength: {
                        min: 6,
                        max: 70,
                        message: 'The name must be more than 6 and less than 70 characters long'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9_\.\s]+$/,
                        message: 'The name can only consist of alphabetical, number, dot, spaces and underscore'
                    }
                }
            },

            description: {
                message: 'The description is not valid',
                validators: {
                    notEmpty: {
                        message: 'The description is required and can\'t be empty'
                    },
                    stringLength: {
                        min: 6,
                        max: 160,
                        message: 'The description must be more than 6 and less than 160 characters long'
                    }
                }
            },
            price: {
                message: 'The price is not valid',
                validators: {
                    notEmpty: {
                        message: 'The price is required and can\'t be empty'                
                    },                  
                    regexp: {
                        regexp: /^\d+(,\d{1,2})?$/,
                        message: 'The price can only consist of digits or , to indicate fraction values'
                    }
                }
            }
    });
};

function isFormValid(){

    // Get plugin instance
    var bootstrapValidator = $('#myForm').data('bootstrapValidator');

    bootstrapValidator.validate();

    // validate and then call method is Valid to check results
    return  bootstrapValidator.isValid();
};

您可以將以上代碼封裝在requireJS模塊或JS名稱空間中,甚至封裝在角度服務中。 在您的控制器中,您可以調用“ isFormValid”來檢查所有輸入對於該特定形式是否正確:

/* callback for ng-click on your controller: */
$scope.saveRecord = function () {
  // validate fields
  if (isFormValid()) {
      MyService.save($scope.record);
      // ...
  }    
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM