角JS:验证表单字段之前提交

角JS:验证表单字段之前提交

问题描述:

我在建设有2步形式的角度JS应用程序。这真的只是一个形式,而是使用JavaScript来隐藏第一面板和显示第二,当用户点击下一步按钮,并转到步骤2.我已经设置在步骤1中必要的一些字段的验证,但很明显,他们当用户点击下一步按钮,没有得到证实......他们得到验证时,提交按钮时,在步骤2的结尾。

I'm building an Angular JS app with a 2-step form. It's really just one form, but uses JavaScript to hide the first panel and show the second when the user clicks the 'next' button and moves on to step 2. I have set 'required' validations on some of the fields in step 1, but obviously, they do not get validated when the user clicks the 'next' button...they get validated when the 'submit' button is clicked at the end of step 2.

有什么办法,我可以告诉角度来验证表单中这些字段在单击下一步按钮的时候?

Is there any way I can tell angular to validate those fields in the form when the 'next' button is clicked?

我建议使用子表单。 AngularJS支持把一个形式里面又和有效性传播形式下表单上;

I suggest to use sub-forms. AngularJS supports putting one form inside another, and validity is propagated form lower form to upper;

下面是例子:http://plnkr.co/edit/SruBmlGZZtbwiU8cktAp?p=$p$pview

下面是一些code,这样可以抓住的理念是:

Here is some code so you can grasp the idea:

  <form name='myform' ng-init="step = 1">
    <div ng-show="step==1">
      <h3>Step 1: Enter some general info</h3>
      <div ng-form='step1form'>
        Name: <input ng-model="name" required>
      </div>
      <button ng-disabled="!step1form.$valid" ng-click="step = 2">Next</button>
    </div>

    <div ng-show="step==2">
      <h3>Step 2: Final info</h3>
      <div ng-form="step2form">
          Phone: <input ng-model="phone" required>
      </div>
      <button  ng-click="step = 1">Prev</button>
      <button ng-disabled="!myform.$valid" ng-click="submit()">Submit</button>
    </div>
    <div>
      Validation status:
      <div> Whole form valid? {{myform.$valid}} </div>
      <div> Step1 valid? {{step1form.$valid}} </div>
      <div> Step2 valid? {{step2form.$valid}} </div>
    </div>
  </form>