2015-09-24 22 views
8

Tôi đã theo dõi this tutorial về Biểu mẫu nhiều bước AngularJS Sử dụng Bộ định tuyến UI. Biểu mẫu này hoạt động và tôi có thể lưu dữ liệu của mình nhưng bây giờ tôi có câu hỏi về cách xác thực từng bước trong biểu mẫu.AngularJS xác thực biểu mẫu nhiều bước

tôi có các hình thức sau đây với các lĩnh vực đầu vào:

Bước 1

  • Giấy phép tấm

Bước 2

  • Tên
  • đường
  • Niên Giám
  • Thành phố
  • Email
  • Telephone

Bước 3

  • Chọn một thời gian ngày & từ lịch

Có vẻ hơi như thế này:

enter image description here

tôi có một cái nhìn cơ bản nói chung như thế này:

<body ng-app="formApp"> 
    <div id="top"></div> 
    <div class="container"> 
     <!-- views will be injected here --> 
     <div ui-view></div> 

    </div> 
</body> 

Trong app.js của tôi, tôi đã như sau (chưa hoàn chỉnh, còn lại những điều quan trọng không ra):

// app.js 
// create our angular app and inject ngAnimate and ui-router 
// ============================================================================= 
angular.module('formApp', ['ngAnimate', 'ui.router', 'ui.calendar']) 

// configuring our routes 
// ============================================================================= 
.config(function($stateProvider, $urlRouterProvider, $interpolateProvider) { 

    $interpolateProvider.startSymbol('<%'); 
    $interpolateProvider.endSymbol('%>'); 

    $stateProvider 

     // route to show our basic form (/form) 
     .state('form', { 
      url: '/form', 
      templateUrl: 'views/form.html', 
      controller: 'formController' 
     }) 

     // nested states 
     // each of these sections will have their own view 
     // url will be /form/interests 
     .state('form.license', { 
      url: '/license', 
      templateUrl: 'views/form-license.html' 
     }) 

     // url will be nested (/form/profile) 
     .state('form.profile', { 
      url: '/profile', 
      templateUrl: 'views/form-profile.html' 
     }) 

     // url will be /form/payment 
     .state('form.appointment', { 
      url: '/appointment', 
      templateUrl: 'views/form-appointment.html' 
     }) 

     // url will be /form/success 
     .state('form.success', { 
      url: '/success', 
      templateUrl: 'views/form-success.html' 
     }); 

    // catch all route 
    // send users to the form page 
    $urlRouterProvider.otherwise('/form/license'); 
}) 

// our controller for the form 
// ============================================================================= 
.controller('formController', function($scope, $http, $compile, $location, uiCalendarConfig) { 

    $scope.formData = {}; 
    $scope.formData.profile = {}; 


    $scope.next = function(step){ 

     if(step == 1) 
     { 

     } 
     else if(step == 2) 
     { 

     } 
    }; 

    // function to process the form 
    $scope.processForm = function(isValid) { 

    }; 

}); 

form.html chung tôi:

<!-- form.html --> 
<div class="row"> 
    <div class="col-sm-6 col-sm-offset-3"> 

     <div id="form-container"> 
      <form id="appointment-form" name="appointmentform" ng-submit="processForm(appointmentform.$valid)"> 

       <!-- our nested state views will be injected here --> 
       <div id="form-views" ui-view></div> 
      </form> 

     </div> 
    </div> 
</div> 

Bước đầu tiên trong hình thức của tôi là trong form-license.html:

<!-- form-license.html --> 
<label>Nummerplaat ingeven</label> 
<div class="form-group"> 
    <div class="col-xs-8 col-xs-offset-2"> 
     <input required type="text" class="form-control" name="license" ng-model="formData.license"> 

    </div> 
</div> 


<div class="form-group row"> 
    <div class="col-xs-4 col-xs-offset-4"> 
     <a ng-click="next(1)" ui-sref="form.profile" class="btn btn-next btn-block"> 
      Volgende 
     </a> 
    </div> 
</div> 

Nhưng bây giờ tôi tự hỏi làm cách nào để xác thực điều này khi họ nhấp vào nút tiếp theo .... Nó không hoạt động với thuộc tính được yêu cầu bình thường.

Ai đó có thể giúp tôi với điều này?

UPDATE:

Bây giờ tôi có trong bước đầu tiên của tôi như sau:

<div class="col-xs-4 col-xs-offset-4"> 
    <a ng-click="next(1, processForm)" ui-sref="form.profile" ng-disabled="!licenseValidated" class="btn btn-next btn-block"> 
     Volgende 
    </a> 
</div> 

Trong điều khiển của tôi:

var validateLicense = function (newVal) { 
    var validated = false; 
    // Run your custom validation checks 
    if(newVal) 
    { 
     validated = true; 
    } 
    return validated; 
}; 

$scope.$watch('formData.license', function (newVal) { 
    $scope.licenseValidated = validateLicense(newVal); 
}); 

Ok, mà làm việc. Nhưng trong bước thứ hai của tôi, tôi có nhiều trường như sau:

<div class="profile"> 
    <div class="form-group"> 
     <label class="col-sm-3 control-label" for="name">Name</label> 
     <div class="col-sm-9"> 
      <input type="text" class="form-control" name="name" ng-model="formData.profile.name"> 
     </div> 
    </div> 

    <div class="form-group"> 
     <label class="col-sm-3 control-label" for="street">Street</label> 
     <div class="col-sm-9"> 
      <input type="text" class="form-control" name="street" ng-model="formData.profile.street"> 
     </div> 
    </div> 

    <div class="form-group"> 
     <label class="col-sm-3 control-label" for="zipcode">Zipcode</label> 
     <div class="col-sm-9"> 
      <input type="text" class="form-control" name="zipcode" ng-model="formData.profile.zipcode"> 
     </div> 
    </div> 

    <div class="form-group row"> 
     <div class="col-xs-8 col-xs-offset-2"> 
      <a ng-click="next(1)" ui-sref="form.license" class="btn btn-block btn-previous col-xs-3"> 
       VORIGE 
      </a> 
      <a ng-click="next(2)" ui-sref="form.appointment" class="btn btn-block btn-next col-xs-3"> 
       Volgende 
      </a> 
     </div> 
    </div> 
</div> 

Tôi có cần phải tạo cho mỗi trường trong số đó một $ scope.watch không? Và tôi có cần phải thêm chúng vào ng-vô hiệu hóa nút của tôi không?

Trả lời

5

Bạn chỉ có thể vô hiệu hóa các nút bên cạnh nếu bất kỳ bước xác thực nào không vượt qua.

Cái gì như:

// Inside your controller. 
// Don't overload the scope. 
// Only assign what will be needed through your HTML or other AngularJS Scopes 
var validateLicense = function (newVal) { 
    // If you are only checking for content to be entered 
    return (newVal !== '' && newVal !== undefined); 
}; 
var validateInfo = function (newVal) { 
    if (newVal.length > 0) { 
     // Check to make sure that all of them have content 
     for (var i = 0, l = newVal.length; i < l; i++) { 
      if (newVal[i] === undefined || newVal[i] === '') { 
       return false; 
      } 
     } 
     // We didn't find invalid data, let's move on 
     return true; 
    } 
    return false; 
}; 

var validateDate = function (newVal) { 
    var validated = false; 
    // Run your custom validation checks 
    return validated; 
} 

// Initialize the disabled "Next" buttons 
$scope.licenseValidated = false; 
$scope.infoValidated = false; 

// Watch a single item in a form, if filled in we will let them proceed 
$scope.$watch('formData.license', function (newVal) { 
    $scope.licenseValidated = validateLicense(newVal); 
}); 

// Watch a multiple items in a form, if ALL are filled in we will let them proceed 
// Note that the order in this array is the order the newVal will be, 
// So further validation for formData.number would be on newVal[1] 
$scope.$watchGroup(['formData.name', 'formData.number', 'formData.address'], function (newVal) { 
    $scope.infoValidated = validateInfo(newVal); 
}); 

form-license.html thêm thuộc tính ng-disabled vào nút tiếp theo của bạn:

<a ng-click="next(1, appointmentform)" ui-sref="form.profile" class="btn btn-next btn-block" ng-disabled="!licenseValidated"> 
    Volgende 
</a> 

form-info.html lặp lại trên bước

<a ng-click="next(1, appointmentform)" ui-sref="form.profile" class="btn btn-next btn-block" ng-disabled="!infoValidated"> 
    Volgende 
</a> 

Và cứ thế ...

See this Fiddle for Demo

+0

Và bạn có ý nghĩa gì với kiểm tra xác thực tùy chỉnh? Ví dụ, bắt buộc. Chỉ cần kiểm tra: if (newVal) {validated = true; }. Như thế này? – nielsv

+0

Và làm cách nào tôi có thể hiển thị lỗi cho người dùng? – nielsv

+0

Không, 'newVal' là bất kỳ đầu vào nào, nó không phải là đối tượng biểu mẫu để không có kiểm tra' newVal. $ Valid'. Ý tôi là, giả sử bạn muốn đảm bảo rằng giấy phép có ít nhất 20 ký tự và chứa chữ cái và số hoặc thứ gì đó. Bạn có thể làm một bài kiểm tra regex chống lại điều đó. Angular's '. $ Valid' chỉ kiểm tra các tiêu chí rất hạn chế. Giống như nếu có đầu vào hoặc nó trống, vv – jnthnjns

3

Bạn có một vài tùy chọn có sẵn cho bạn tùy thuộc vào cách bạn muốn tiếp cận nó.

Để bắt đầu, bạn nên sử dụng ng-form cho từng bước trong số 3 bước biểu mẫu. Điều này sẽ cho phép bạn xác thực từng cá nhân mà không phải lo lắng về các phần khác.

Vì vậy, như một ví dụ từng hình thức đầu tiên của bạn có thể biến thành:

<ng-form name="LicenseForm"> 
    <label>Nummerplaat ingeven</label> 
    <div class="form-group"> 
     <div class="col-xs-8 col-xs-offset-2"> 
      <input required type="text" class="form-control" name="license" ng-model="formData.license"> 

     </div> 
    </div> 


    <div class="form-group row"> 
     <div class="col-xs-4 col-xs-offset-4"> 
      <a ng-click="next(1, LicenseForm)" ui-sref="form.profile" class="btn btn-next btn-block"> 
       Volgende 
      </a> 
     </div> 
    </div> 
</ng-form> 

Điều này cho phép bạn truy cập vào các tính chất hình thức xác nhận chỉ qua bước này. Tại thời điểm này, bạn có thể cập nhật điều khiển của bạn để sử dụng .$invalid hoặc .$valid trên đối tượng hình thức mà hiện đang được thông qua trong next nút gửi, có nghĩa là bây giờ bạn có thể làm điều gì đó như:

$scope.next = function(step, form) { 
    if (form.$invalid) { 
     console.log('Form is invalid!'); 
     return; 
    } 
    // move to next section 
    ... 
}; 
Các vấn đề liên quan