search
HomeWeb Front-endJS TutorialDetailed explanation of form validation in AngularJS

AngularJS自带了很多验证,什么必填,最大长度,最小长度...,这里记录几个有用的正则式验证

1.使用angularjs的表单验证

正则式验证

只需要配置一个正则式,很方便的完成验证,理论上所有的验证都可以用正则式完成

//javascript
$scope.mobileRegx = "^1(3[0-9]|4[57]|5[0-35-9]|7[01678]|8[0-9])\\d{8}$";
$scope.emailRegx = "^[a-z]([a-z0-9]*[-_]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[\.][a-z]{2,3}([\.][a-z]{2})?$";
$scope.pwdRegx = "[a-zA-Z0-9]*";
<div class="form-group">
<input class="form-control" name="mobile" type="text" ng-model="account.mobile" required ng-pattern="mobileRegx"/>
<span class="error" ng-show="registerForm.$submitted && registerForm.mobile.$error.required">*手机号不能为空</span>
<span class="error" ng-show="registerForm.$submitted && registerForm.mobile.$error.pattern">*手机号地址不合法</span>
</div>
<input type="text" ng-pattern="/[a-zA-Z]/" />

   

数字

设置input的type=number即可

<div class="form-group col-md-6">
<label for="password">
预估时间
</label>
<div class="input-group">
<input required type="number" class="form-control" ng-model="task.estimated_time" name="time" />
<span class="input-group-addon">分钟</span>
</div>
<span class="error" ng-show="newTaskForm.$submitted && newTaskForm.time.$error.required">*请预估时间</span>
</div>

   

邮箱

<input type="email" name="email" ng-model="user.email" />

   

URL

<input type="url" name="homepage" ng-model="user.facebook_url" />

   

效果

效果是实时的,很带感

Detailed explanation of form validation in AngularJS

2.使用ngMessages验证表单

angular.module(&#39;ngMessagesExample&#39;, [&#39;ngMessages&#39;]);
<form name="myForm">
<label>
Enter your name:
<input type="text"
name="myName"
ng-model="name"
ng-minlength="5"
ng-maxlength="20"
required />
</label>
<pre class="brush:php;toolbar:false">myForm.myName.$error = {{ myForm.myName.$error | json }}
 
You did not enter a field
Your field is too short
Your field is too long

简直是第二次解放啊。。。

Detailed explanation of form validation in AngularJS

2.动态生成的表单的验证

如果你有一部分form的内容是动态生成的,数量和名字都不确定的时候,该如何验证这些生成的元素呢?其实维护一个动态的form本来就是个问题。但是在angular中,只需要记住一点:准备好你的数据,其他的交给angular。像下面这个例子,你只需要维护好一个数组,然后利用ng-repeat就可以快速的呈现到页面上。

Detailed explanation of form validation in AngularJS

Detailed explanation of form validation in AngularJS

其实动态的form和一般的form验证都是一致的,只是动态的form需要使用myForm[inout_name].$error的形式访问

<!-- 动态显示状态的负责人 -->
<div class="form-group col-md-6" ng-repeat="sta in task.status_table | orderBy : sta.sequence_order">
<label>{{sta.status_name}} 负责人</label>
<select required class="form-control" ng-model="sta.user_id" ng-options="qa.id as qa.last_name+&#39; &#39;+qa.last_name for qa in taskUserList" name="{{sta.status_name}}">
</select>
<div ng-messages="newTaskForm[sta.status_name].$error" ng-if="newTaskForm.$submitted || newTaskForm[sta.status_name].$touched">
<p class="error" ng-message="required">*请选择负责人</p>
</div>
</div>

   

3. 必填项加亮显

有些表单我们不希望粗暴的在下面添加文字信息提示验证,而是希望更简洁的方式,如:加亮边框,突出显示

Detailed explanation of form validation in AngularJS

需要做的只是在required验证没通过的时候添加class,改变元素的样式即可

<form name="loginForm" novalidate ng-submit="loginPost()" class="navbar-form navbar-right" ng-hide="login">
<fake-autocomplete></fake-autocomplete>
<div class="form-group">
<input name="user_name" required maxlength="50" type="text" class="form-control" placeholder="手机号或邮箱" ng-model="account.user_name" ng-class="{warn:loginForm.$submitted && loginForm.user_name.$error.required}">
</div>
<div class="form-group">
<input name="password" required type="password" maxlength="50" placeholder="密码" ng-model="account.password" ng-class="{&#39;form-control&#39;:1,warn:loginForm.$submitted && loginForm.password.$error.required}">
</div>
<button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-lock"></span> 登录</button>
</form>
.warn {
border-color: #f78d8d !important;
outline: 0 !important;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgb(239, 154, 154) !important;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 8px rgba(239, 154, 154) !important;
}

   


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools