简体   繁体   English

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

[英]Angular JS: Validate form fields before submit

I'm building an Angular JS app with a 2-step form. 我正在构建一个两步形式的Angular JS应用程序。 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. 它实际上只是一种形式,但是当用户单击“下一步”按钮并使用“步骤”时,使用JavaScript隐藏第一个面板并显示第二个面板。我已在步骤1中的某些字段上设置了“必需”验证,但显然,当用户点击“下一步”按钮时,它们不会得到验证......当在步骤2结束时单击“提交”按钮时,它们会得到验证。

Is there any way I can tell angular to validate those fields in the form when the 'next' button is clicked? 当点击“下一步”按钮时,有什么方法可以告诉角度来验证表格中的那些字段吗?

I suggest to use sub-forms. 我建议使用子表格。 AngularJS supports putting one form inside another, and validity is propagated form lower form to upper; AngularJS支持将一个表单放在另一个表单中,并且有效性从下层传播到上层;

Here is example: http://plnkr.co/edit/SruBmlGZZtbwiU8cktAp?p=preview 以下是示例: http//plnkr.co/edit/SruBmlGZZtbwiU8cktAp?p = preview

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM