如何使用bootstrap和angular form逐步验证表单?

时间:2012-12-31 05:36:11

标签: javascript node.js twitter-bootstrap angularjs

我找到了这个例子step-by-step form with bootstrap and angularjs

如何在跳转到第2步之前验证电子邮件? 或阻止步骤跳转直到字段已满?

function RegisterCtrl($scope, $location) {

  $scope.steps = [
    'Step 1: Team Info',
    'Step 2: Campaign Info',
    'Step 3: Campaign Media'
  ];

....some code

2 个答案:

答案 0 :(得分:1)

首先,在控制器中定义模型:

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)以突出显示该字段。

http://jsfiddle.net/xayzP/

答案 1 :(得分:1)

您应该使用directives来测试您的表单字段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对象无效,则可以显示错误消息:

<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.$invalid上的ng-class停用下一个链接,直到表单生效为止:

<li ng-class="{disabled: myForm.$invalid}" >
   <a ng-model="next" ng-click="incrementStep(myForm)">Next Step &rarr;</a>
</li>

请参阅example