angularjs表单验证

We have updated this article for Angular 1.3 and the new ng-touched feature.
我们已经为Angular 1.3和新的ng-touched功能更新了本文。

Today we'll be looking at at the ways that Angular helps us do form validations. We'll be talking more on forms using Angular (just like our other article: Submitting AJAX Forms: The AngularJS Way). Don't worry though, that article is not required.

今天,我们将研究Angular帮助我们进行表单验证的方式。 我们将更多地讨论使用Angular的表单(就像我们其他文章: 提交AJAX表单:AngularJS Way一样 )。 不过请放心,该文章不是必需的。

We'll focus on client side validation and using the built in Angular form properties. Here's a quick demo.

我们将专注于客户端验证并使用内置的Angular表单属性。 这是一个快速演示。

演示版 (Demo)

See the Pen AngularJS Form Validation by Chris Sevilleja (@sevilayha) on CodePen

在CodePen上查看 Chris Sevilleja ( @sevilayha )的Pen AngularJS表单验证

要求 (Requirements)

  • Name is required名称为必填项
  • Username is not required, minimum length 3, maximum length 8不需要用户名,最小长度3,最大长度8
  • Email is not required, but has to be a valid email电子邮件不是必需的,但必须是有效的电子邮件
  • Form submit is disabled if the form isn't valid如果表单无效,则禁用表单提交
  • Show a required or invalid email error显示必填或无效的电子邮件错误
  • Alert awesome if submitted correctly如果提交正确,将为您带来震撼的提醒

Now that we know what we want, let's get to building.

现在我们知道了我们想要什么,让我们开始构建。

角形属性$ valid,$ invalid,$ pristine,$ dirty (Angular Form Properties $valid, $invalid, $pristine, $dirty)

Angular provides properties on forms that help us validate them. They give us various information about a form or its inputs and are applied to a form and inputs.

Angular在表单上提供属性以帮助我们验证它们。 它们为我们提供了有关表单或其输入的各种信息,并应用于表单和输入

Property Class Description
$valid ng-valid Boolean Tells whether an item is currently valid based on the rules you placed.
$invalid ng-invalid Boolean Tells whether an item is currently invalid based on the rules you placed.
$pristine ng-pristine Boolean True if the form/input has not been used yet.
$dirty ng-dirty Boolean True if the form/input has been used.
$touched ng-touched Boolean True if the input has been blurred.
属性 描述
$有效 ng有效 布尔值根据您放置的规则告诉项目当前是否有效。
$无效 ng无效 布尔值根据您放置的规则判断当前某项是否无效。
原始的 ng-原始 Boolean如果表单/输入尚未使用。
$脏 ng-dirty 如果表单/输入已经使用布尔真。
$感动 触摸 Boolean如果输入已经模糊。

Angular also provides classes on the form and its inputs so that you can style each state accordingly.

Angular还提供了表单及其输入中的类,以便您可以相应地设置每个状态的样式。

访问角形属性 (Accessing Angular Form Properties)

  • To access the form: <form name>.<angular property>要访问表单: <form name>.<angular property>
  • To access an input: <form name>.<input name>.<angular property>要访问输入: <form name>.<input name>.<angular property>

设置表格 (Setting Up Our Form)

We will use a simple form to demonstrate.

我们将使用一个简单的表格进行演示。

We will need 2 files: * index.html Our code to display the form * app.js Our Angular application and controller (barely any code at all)

我们将需要2个文件 :* index.html我们的代码以显示表单* app.js我们的Angular应用程序和控制器(几乎没有任何代码)

我们的表格代码index.html (Our Form Code index.html)

<!-- index.html -->
<!DOCTYPE html>
<html>
<head><!-- CSS ===================== --><!-- load bootstrap --><link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"> <style>body    { padding-top:30px; }</style><!-- JS ===================== --><!-- load angular --><script src="http://code.angularjs.org/1.2.6/angular.js"></script> <script src="app.js"></script>
</head><!-- apply angular app and controller to our body -->
<body ng-app="validationApp" ng-controller="mainController">
<div class="container">
<div class="col-sm-8 col-sm-offset-2"><!-- PAGE HEADER --><div class="page-header"><h1>AngularJS Form Validation</h1></div><!-- FORM --><!-- pass in the variable if our form is valid or invalid --><form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate> <!-- novalidate prevents HTML5 validation since we will be validating ourselves --><!-- NAME --><div class="form-group"><label>Name</label><input type="text" name="name" class="form-control" ng-model="name" required></div><!-- USERNAME --><div class="form-group"><label>Username</label><input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8"></div><!-- EMAIL --><div class="form-group"><label>Email</label><input type="email" name="email" class="form-control" ng-model="email"></div><!-- SUBMIT BUTTON --><button type="submit" class="btn btn-primary">Submit</button></form></div><!-- col-sm-8 -->
</div><!-- /container -->
</body>
</html>

A few key points to note here:

这里需要注意的几个关键点:

@media (max-width: 1280px) { .go-go-gadget-react img:first-child { display: none; } }@media (max-width: 780px) {.go-go-gadget-react { flex-direction: column; }.go-go-gadget-react img { margin-left: 0 !important; margin-bottom: 12px !important; }.header-thingy { margin-top: 20px; }.button-thingy { margin-left: 0 !important; margin-top: 12px !important; }} @media (max-width: 1280px) { .go-go-gadget-react img:first-child { display: none; } }@media (max-width: 780px) {.go-go-gadget-react { flex-direction: column; }.go-go-gadget-react img { margin-left: 0 !important; margin-bottom: 12px !important; }.header-thingy { margin-top: 20px; }.button-thingy { margin-left: 0 !important; margin-top: 12px !important; }}

  • novalidate: This will prevent the default HTML5 validations since we'll be doing that ourselves (ours will be much prettier)novalidate :这将阻止默认HTML5验证,因为我们将自己做(我们会更漂亮)
  • We have applied ng-model to our inputs so that we have data from our forms bound to Angular variables我们已将ng-model应用于输入,以便将表格中的数据绑定到Angular变量
  • ng-minlength and ng-maxlength on username will create those rules用户名上的ng-minlengthng-maxlength将创建这些规则
  • The name input is requiredname输入为必填项
  • The email input is type="email"email输入为type =“ email”

验证规则 (Validation Rules)

Angular provides many validation rules that we can use in addition to ng-minlength and ng-maxlength.

Angular除了ng-minlengthng-maxlength之外,还提供了许多验证规则。

These are the available parameters for an Angular input to create validation rules. Read the Angular input directive for more information.

这些是Angular输入创建验证规则的可用参数。 阅读Angular输入指令以获取更多信息。

<inputng-model="{ string }"name="{ string }"requiredng-required="{ boolean }"ng-minlength="{ number }"ng-maxlength="{ number }"ng-pattern="{ string }"ng-change="{ string }"></input>

Now that we have our simple form, let's create our Angular app and controller that we have already applied to it using ng-app and ng-controller.

现在我们有了简单的表单,让我们使用ng-appng-controller创建已经应用到它的Angular应用ng-appng-controller

我们的Angular应用代码app.js (Our Angular App Code app.js)

// app.js
// create angular app
var validationApp = angular.module('validationApp', []);// create angular controller
validationApp.controller('mainController', function($scope) {// function to submit the form after all validation has occurred            $scope.submitForm = function(isValid) {// check to make sure the form is completely validif (isValid) {alert('our form is amazing');}};});

禁用HTML5验证novalidate (Disabling HTML5 Validation novalidate)

We will use novalidate on our form. This is a good practice since we will handle the validation ourselves. If we let our form do it, it will look pretty ugly.

我们将在表单上使用novalidate 。 这是一个好习惯,因为我们将自己处理验证。 如果我们让表单执行此操作,它将看起来非常难看。

禁用提交按钮ng-disabled (Disabling the Submit Button ng-disabled)

Now the real fun begins. We get to start using Angular properties. First let's disable our submit button. We only want it disabled if our form is $invalid.

现在,真正的乐趣开始了。 我们开始使用Angular属性 。 首先,让我们禁用提交按钮。 我们只希望在表单为$invalid时禁用它。

<!-- index.html -->
...<!-- SUBMIT BUTTON -->
<button type="submit" class="btn btn-primary" ng-disabled="userForm.$invalid">Submit</button>...

With just that little code (ng-disabled), our form button will be disabled if the form is $invalid. This means that our name input field is required and our email input field requires a valid email.

仅需少量代码( ng-disabled ),如果表单为$invalid ,我们的表单按钮将被禁用。 这意味着我们的name输入字段是必需的,而我们的email输入字段则需要一个有效的电子邮件。

显示错误消息ng-show (Showing an Error Message ng-show)

ng-valid and ng-invalid will automatically determine if an input is good based on the rules placed on it in your form.

ng-validng-invalid会根据表格中输入的规则自动确定输入是否正确。

Let's go through and add an error message for each of our inputs if they are not $valid and have already been used (since we don't want to show an error before they've been used).

如果每个输入不是$valid且已被使用(因为我们不想在使用它们之前显示错误),我们就为每个输入添加一条错误消息。

<!-- index.html -->
...<!-- NAME -->
<div class="form-group"><label>Name</label><input type="text" name="name" class="form-control" ng-model="name" required><p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">You name is required.</p>
</div><!-- USERNAME -->
<div class="form-group"><label>Username</label><input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8"><p ng-show="userForm.username.$error.minlength" class="help-block">Username is too short.</p><p ng-show="userForm.username.$error.maxlength" class="help-block">Username is too long.</p>
</div><!-- EMAIL -->
<div class="form-group"><label>Email</label><input type="email" name="email" class="form-control" ng-model="email"><p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p>
</div>...

Just like that, Angular will automatically determine if we should show an error based on an inputs $invalid and $pristine properties.

这样,Angular将根据输入$invalid$pristine属性自动确定是否显示错误

Better Validation Messages: There is now a new way to show error messages. 更好的验证消息 :现在有一种显示错误消息的新方法。 AngularJS Form Validation with ngMessages 使用ngMessages进行AngularJS表单验证

样式类 (Styling Classes)

Angular already provides classes on our inputs and our forms based on if they are valid or not. Look at the table at the beginning of this article for those classes (ng-valid, ng-invalid, ng-pristine and ng-dirty).

Angular已经根据输入和表单的有效与否提供了类。 请查看本文开头的表,以了解这些类( ng-validng-invalidng-pristineng-dirty )。

You can style those in CSS if you like. You can do anything you like with those classes. There will even be classes based on the certain rules applied if you wanted to get really specific.

您可以根据需要在CSS中设置样式。 您可以使用这些课程做任何您喜欢的事情。 如果您想变得非常具体,甚至会根据所应用的某些规则进行分类。

.ng-valid       {  }
.ng-invalid     {  }
.ng-pristine    {  }
.ng-dirty       {  }
.ng-touched     {  }/* really specific css rules applied by angular */
.ng-invalid-required        {  }
.ng-invalid-minlength       {  }
.ng-valid-max-length        {  }

添加条件类ng-class (Adding Conditional Classes ng-class)

Since we are using Bootstrap, we will use the classes they provide (has-error). This will get us that nice error and color around our form-group.

由于我们使用的是Bootstrap ,我们将使用它们提供的类( has-error )。 这将使我们在form-group周围得到很好的错误和颜色。

ng-class allows us to add classes based on an expression. In this case, we want to add a has-error class to our form-group if an input is $invalid and not pristine.

ng-class允许我们基于表达式添加类。 在这种情况下,如果输入是$invalid而不是pristine ,我们想在表单组中添加一个has-error类。

The way it works is ng-class="{ <class-you-want> : <expression to be evaluated > }". For more information, read the Angular ngClass docs.

它的工作方式是ng-class="{ <class-you-want> : <expression to be evaluated > }" 。 有关更多信息,请阅读Angular ngClass docs 。

<!-- index.html -->
...<!-- NAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }"><label>Name</label><input type="text" name="name" class="form-control" ng-model="user.name" required><p ng-show="userForm.name.$invalid && !userForm.name.$pristine" class="help-block">You name is required.</p>
</div><!-- USERNAME -->
<div class="form-group" ng-class="{ 'has-error' : userForm.username.$invalid && !userForm.username.$pristine }"><label>Username</label><input type="text" name="username" class="form-control" ng-model="user.username" ng-minlength="3" ng-maxlength="8"><p ng-show="userForm.username.$error.minlength" class="help-block">Username is too short.</p><p ng-show="userForm.username.$error.maxlength" class="help-block">Username is too long.</p>
</div><!-- EMAIL -->
<div class="form-group" ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$pristine }"><label>Email</label><input type="email" name="email" class="form-control" ng-model="user.email"><p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p>
</div>...

Now our form has the correct Bootstrap error classes.

现在,我们的表单具有正确的Bootstrap错误类。

提交表单后仅显示错误 (Only Showing Errors After Submitting the Form)

Sometimes it is not desirable to show errors while a user is typing. The errors currently show immediately as a user is typing into the form. This happens because of Angular's great data-binding feature. Since everything changes immediately, it can be a downside when talking about form validation.

有时不希望在用户键入时显示错误。 当用户键入表单时,错误当前会立即显示。 发生这种情况是因为Angular具有强大的数据绑定功能。 由于一切都会立即改变,因此在谈论表单验证时可能会有不利之处。

For the scenario where you only want to show errors after a form is submitted, you would adjust the above code a little bit.

对于只希望在提交表单后显示错误的情况,可以对上面的代码进行一些调整。

  1. You would need to take away the ng-disabled on the submit button since we want a user to be able to submit a form even if it is not fully valid.您需要ng-disabled “提交”按钮上的ng-disabled ,因为我们希望用户即使表单不是完全有效也可以提交表单。
  2. You would add a variable after the form has been submitted. Inside of your submitForm() function, just add $scope.submitted = true;. This stores the submitted variable as true as soon as the form is submitted.提交表单后,您将添加一个变量。 在您的submitForm()函数内部,只需添加$scope.submitted = true; 。 提交表单后,这会将提交的变量存储为true。
  3. Adjust the error rules from ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }" to ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine && submitted }". This ensures that the error will only show after the form is submitted. You would need to adjust all the other ng-class and ng-show to account for this variable.将错误规则从ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine }"ng-class="{ 'has-error' : userForm.name.$invalid && !userForm.name.$pristine && submitted }" 。 这样可以确保仅在提交表单后才显示错误。 您需要调整所有其他ng-classng-show来解决此变量。

Now the form only shows errors if the submitted variable is set to true.

现在,如果submitted变量设置为true则表单仅显示错误。

单击输入后仅显示错误 (Only Showing Errors After Clicking Out of an Input)

Only showing errors after clicking out of an input (also known as blur) is a little more complicated than validating on submit. Validating a form on blur requires a custom directive. A directive will allow you to manipulate the DOM.

仅在单击输入后才显示错误(也称为 blur ),比对提交进行验证要复杂一些。 验证表单模糊需要一个 自定义指令 。 指令将允许您操纵DOM。

We have updated this article to add the new ng-touched feature in Angular 1.3. This helps us handle blurred inputs!

我们更新了本文,在Angular 1.3中添加了新的ng-touched功能。 这可以帮助我们处理模糊的输入!

全做完了 (All Done)

Now once we fill out all our information correctly, our form submit button will be active. Once we submit our form, we'll see the alert message we set up.

现在,一旦我们正确填写了所有信息,我们的表单提交按钮将处于活动状态。 提交表单后,我们将看到我们设置的提醒消息。

With just a few simple lines we now have:

现在只有几行简单的代码:

  • Input Validation输入验证
  • Form Errors表格错误
  • Custom Classes自订课程
  • Automatically disabled and enabled form自动禁用和启用表格
  • Custom Rules自订规则

As you can see, it is easy to use the built in Angular form validation techniques to create a client-side validated form.

如您所见,很容易使用内置的Angular表单验证技术来创建客户端验证的表单。

未来 (The Future)

As it stands, it is not a simple process to do validation after a user clicks out of an input. The Angular team is aware of this and they have said they plan to add more states to handle things like form.submitted, input.$visited, input.$blurred, or input.$touched. Here are some resources for the future of form validation:

就目前而言, 在用户单击输入之后进行验证不是一个简单的过程。 Angular团队已经意识到了这一点,他们已经表示计划增加更多状态来处理诸如form.submittedinput.$visitedinput.$blurredinput.$touched类的事情。 以下是将来进行表单验证的一些资源:

  • Github IssueGithub问题
  • ngForm Module IdeasngForm模块创意

Hopefully sooner rather than later it'll be easier to do validation and account for different states of our application.

希望早日而不是晚日,进行验证并考虑应用程序的不同状态会更加容易。

Edit #1: Added information about validating after form submit or on blur. Also added resources. 编辑#1 :添加了有关在表单提交后或模糊时进行验证的信息。 还增加了资源。 Edit #2: Changed the process form function to take the valid parameter. Helps to create testable controllers. Thanks to 编辑2 :将过程表单功能更改为采用有效参数。 帮助创建可测试的控制器。 感谢 Fredrik Bostrom for the tip. Fredrik Bostrom的小费。
AngularJS Forms series.AngularJS Forms系列的一部分。

  • Submitting AJAX Forms: The AngularJS Way 提交AJAX表单:AngularJS方式
  • AngularJS Form Validation (this article) AngularJS表单验证(本文)
  • Handling Checkboxes and Radio Buttons in Angular Forms 以角形式处理复选框和单选按钮

翻译自: https://scotch.io/tutorials/angularjs-form-validation

angularjs表单验证

angularjs表单验证_AngularJS表单验证相关推荐

  1. Form表单提交前进行JS验证的3种方式

    1. 提交按钮的onclick事件中验证 <script type="text/javascript">          function check(form) { ...

  2. ExtJs 备忘录(3)—— Form表单(三) [ 数据验证 ]

    正文 一.资料 1.1. 表单提示的方式设置,如: Ext.form.Field.prototype.msgTarget='side' 该设置为枚举值:'qtip','side','title','u ...

  3. 重置表单验证 清除表单校验信息

    重置表单验证 清除表单校验信息 提交表单验证的时间经常遇见的一个问题 再次打开时表单验证依旧存在,这种就很烦,用户体验有点差, 在使用Vant或Element UI框架时经常会遇到,再次打开表单时,原 ...

  4. php 自动验证表单类,thinkPHP 表单自动验证功能

    昨天晚上我们老大叫我弄表单自动验证功能,愁了半天借鉴了好多官网的知识,才出来,诶,总之分享一下我自己的成果吧! thinkphp 在Model基类为我们定义了自动验证的函数和正则表达式,我们只需要在对 ...

  5. php ci提交表单验证,ci表单验证代码

    概述 这是只考虑php对表单数据的接收处理.至于js部分以前会结合validate来讲解下 在解释 CodeIgniter 的数据验证处理之前,让我们先描述一下一般的情况: 一个表单显示了. 你填写并 ...

  6. struts上传文件,验证失败表单数据丢失的原因

    struts上传文件,验证失败表单数据丢失的原因 发现一个问题,使用struts进行文件上传,如果有些参数没有完全定义在ActionForm中,需要从request.getParameter获取,在表 ...

  7. html表单提交前验证,jquery表单提交前实现同步验证(附代码)

    jquery表单提交前实现同步验证 .int{ height: 30px; text-align: left; width: 600px; } label{ width: 200px; margin- ...

  8. 验证部分表单是否重复

    1. 效果 图片中的名称.机构编码需要进行重复验证 2. 思路及实现 表单验证 在获取数据将需要验证的表单数据进行保存 this.nameChangeTemp = response.data.orgN ...

  9. html 表单js验证,JavaScript使用表单元素验证表单

    第一章:使用JavaScript验证表单 JavaScript的主要作用:验证表单 1最简单的表单验证-禁止空白的必填项目 1.1最简单的HTML结构 网站最基础的就是注册,它是一个系统的交互基础. ...

最新文章

  1. 计算机网络工程实用技术考试,计算机网络实用技术期中考试复习题.doc
  2. CVPR坐实华人主场:包揽全部奖项,四成作者来自中国,清华商汤领衔,专门设奖致敬黄煦涛...
  3. MVC与Validate验证提示的样式修改
  4. android+p+华为手机,给1.9亿用户32款老机型进行安卓P升级 华为值吗?
  5. 第一次在Linux系统上操作mysql数据库,看完这篇轻松应对
  6. SPOJ1812(后缀自动机求n个串的最长公共子串)
  7. andorid程序UI线程下开启子线程闪退错误解决
  8. Netty源码注释翻译-Channel类
  9. SSIS变量属性中EvaluateAsExpression设置的作用
  10. 全球数据库--基金/管理产品--分类/行业平均
  11. PHP中逻辑运算符的高效用法---和||
  12. pb将datawindow数据导出EXCEL
  13. arcgis 批量计算几何_GIS中的计算几何
  14. 微信小程序实现刷脸登录
  15. 择时 配置 选股0909
  16. linux 跨平台查询 lxr,利用LXR来生成Linux内核代码的交叉索引页面
  17. SSM医院移动收费运维平台毕业设计源码161045
  18. [第0章]欢迎使用CSDN-markdown编辑器(新)
  19. Mac 查看本机ip地址
  20. Algorand以2.4美元结束首轮拍卖,为私募价48倍

热门文章

  1. ERP与CRM、MRP、PLM、APS、MES、WMS、SRM的关系
  2. IOS开发之滤镜 CIImage、CIFilter
  3. 为XV6系统扩展一个系统调用需要修改的文件
  4. C语言基于FOC控制算法和STM32主控芯片的双路直流无刷电机控制器源码
  5. 编写代码的软件用什么编写的_您到底是为谁编写代码?
  6. MAC地址的正则表达式
  7. java 的 clear 和 compact
  8. 基础邮件原理(MUA,MTA,MDA)
  9. 通俗理解数学的七大难题及希尔伯特23个数学问题
  10. 宋词欣赏 -- 李清照词全集