Angular JS:提交前验证表单字段 [英] Angular JS: Validate form fields before submit

查看:37
本文介绍了Angular JS:提交前验证表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个两步表单的 Angular JS 应用程序.它实际上只是一个表单,但使用 JavaScript 来隐藏第一个面板,并在用户单击下一步"按钮并转到第 2 步时显示第二个面板.我在第 1 步中的某些字段上设置了必需"验证,但显然,当用户单击下一步"按钮时,它们不会得到验证……当在第 2 步结束时单击提交"按钮时,它们会得到验证.

当单击下一步"按钮时,有什么方法可以告诉 angular 验证表单中的这些字段?

解决方案

我建议使用子表单.AngularJS 支持将一种形式放入另一种形式中,并且有效性从下层形式传播到上层;

示例如下:http://plnkr.co/edit/SruBmlGZZtbwiU8cktAp?p=preview

这是一些代码,以便您可以理解这个想法:

 
<div ng-show="step==1"><h3>步骤 1:输入一些一般信息</h3><div ng-form='step1form'>名称:<input ng-model="name" required>

<button ng-disabled="!step1form.$valid" ng-click="step = 2">下一步</button>

<div ng-show="step==2"><h3>步骤 2:最终信息</h3><div ng-form="step2form">电话:<input ng-model="phone" required>

<button ng-click="step = 1">上一页</button><button ng-disabled="!myform.$valid" ng-click="submit()">提交</button>

<div>验证状态:<div>整个表格有效吗?{{myform.$valid}} </div><div>Step1 有效吗?{{step1form.$valid}} </div><div>Step2 有效吗?{{step2form.$valid}} </div>

</表单>

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?

解决方案

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

Here is example: 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>

这篇关于Angular JS:提交前验证表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆