[英]How to validate forms step by step with bootstrap and angular form?
我通過bootstrap和angularjs找到了這個示例一步一步的表單
如何在跳轉到第2步之前驗證電子郵件? 或阻止步驟跳轉直到字段已滿?
function RegisterCtrl($scope, $location) {
$scope.steps = [
'Step 1: Team Info',
'Step 2: Campaign Info',
'Step 3: Campaign Media'
];
....some code
首先,在控制器中定義模型:
function RegisterCtrl($scope, $location) {
$scope.step1 = {
name: '',
email: '',
password: '',
passwordc: ''
};
//...
將它綁定到您的表單字段:
<input type="text" id="inputEmail" ng-model="step1.email" placeholder="Email">
接下來,在gotoStep()中進行驗證:
$scope.goToStep = function(index) {
if (!$scope.step1.email.match(/[a-z0-9\-_]+@[a-z0-9\-_]+\.[a-z0-9\-_]{2,}/)) {
return window.alert('Please specify a valid email');
}
//...
顯然警報並不好,所以使用jQuery來focus()
並添加Bootstrap類( control-group warning
)以突出顯示該字段。
您應該使用指令來測試您的表單字段vadility,例如:
app.directive('email', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
if (viewValue && viewValue.match(/[a-z0-9\-_]+@[a-z0-9\-_]+\.[a-z0-9\-_]{2,}/)) {
// it is valid
ctrl.$setValidity('email', true);
return viewValue;
} else {
// it is invalid, return undefined (no model update)
ctrl.$setValidity('email', false);
return undefined;
}
});
}
};
});
在您的html中,您需要將指令添加到輸入字段。 如果某個字段使用myForm.email.$error
無效,您可以顯示錯誤消息myForm.email.$error
對象:
<input type="text" name="email" id="inputEmail" placeholder="Email" ng-model="email" email required>
<span ng-show="myForm.email.$error.email" class="help-inline">Email invalid</span>
<span ng-show="myForm.email.$error.required" class="help-inline">Email required</span>
您可以通過使用myForm禁用下一個鏈接,直到表單有效。$ ng對ng-class 無效 :
<li ng-class="{disabled: myForm.$invalid}" >
<a ng-model="next" ng-click="incrementStep(myForm)">Next Step →</a>
</li>
見例子 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.