用angular中的angular-messages(ngMessage)实现表单验证时输入框外提示信息的显示与隐藏(直接把代码粘贴到新建的html文件中即可实现)

寻技术 Html/CSS / Angular 2023年07月11日 87

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="//cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="//cdn.bootcss.com/angular.js/1.5.8/angular.min.js"></script>
<script src="//cdn.bootcss.com/angular-messages/1.5.8/angular-messages.min.js"></script>
</head>
<body ng-app="myApp">

<div class="container">
<div class="col-md-4 col-md-offset-4">
<form class="form-horizontal" novalidate name="signupForm" ng-controller="SignupController">
<div class="form-group" ng-class="{'has-success': signupForm.username.$valid, 'has-error': signupForm.username.$invalid && signupForm.username.$dirty}">
<label class="control-label">Username</label>
<input type="text" name="username" class="form-control" ng-model="user.username" required ng-minlength="5" ng-maxlength="12">
<div class="help-block" ng-show="signupForm.username.$dirty && signupForm.username.$error.minlength">
用户名不能少于5个字符呀,魂淡~
</div>
<div class="help-block" ng-show="signupForm.username.$dirty && signupForm.username.$error.maxlength">
用户名不能多于12个字符~魂淡
</div>
<!-- <pre><code>{{signupForm.username.$error}}</code></pre> -->
</div>
<div class="form-group" ng-class="{'has-success': signupForm.password.$valid && signupForm.password.$dirty, 'has-error': signupForm.password.$invalid && signupForm.password.$dirty}">
<label class="control-label">Password</label>
<input type="password" name="password" class="form-control" ng-model="user.password" ng-required="required" ng-minlength="6" ng-maxlength="13">
<div class="help-block" ng-messages="signupForm.password.$dirty && signupForm.password.$error">
<div ng-message="required">魂淡!密码不能为空!</div>
<div ng-message="minlength">魂淡!密码不能少于6个字符</div>
<div ng-message="maxlength">魂淡~密码需要那么长么~!</div>
</div>
</div>
<div class="form-group">
<button type="button" class="btn btn-success form-control">提交</button>
</div>
</form>
</div>
</div>

<script>
var app = angular.module('myApp', ['ngMessages']);
app.controller('SignupController', ['$scope', function($scope){
$scope.user = {};
$scope.required = true;
console.log(signupForm.$error);
}])
</script>
</body>
</html>

关闭

用微信“扫一扫”