本人即将大四,小白一个,这是第一次在学习论坛上写点东西,因为想养成一个随时记录自己学习进程的好习惯。因为公司里使用的是Angular,so断断续续学习了半个月左右,现在到了检验的时候。
一些Angular基础的标签我就不说了,先从我比较感兴趣也是比较简单的表单验证开始入门吧。
(大神就还是不要往下看啦0.0)
首先,构建的表单几点要求:
1.确保form上标签有一个name属性,像下面的例子一样。最好再加一个novalidate=”novalidate”,此属性是为了验证表单时禁止使用表单自身的验证方法;
2.form中不能有action属性,提交交由ng-submit处理(我这里好像是直接改成了ng-click);
3.每个input一定要有ng-model,最好有一个name方便引用。然后用require或者ng-minlength之类才起作用;
4.novalidate="novalidate",关闭原有的html5表单验证;
先上几张截图:
登录界面注册界面登录界面的验证有:所有字段的空验证,合法性验证,位数验证等;用户名和密码在angular控制器中与后台数据库交互,简单的判断是否存在该用户;
注册界面验证:所有字段的空验证,合法性验证,位数验证等;用户名在controller中验证是否数据库中存在相同的用户名;两次密码的输入是否一致等;
因为是很简单的练手demo,代码也就没那么规范啦:)
代码区
test19.html //登录界面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>angular验证 前台登录页面</title>
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div class="container" style="width: 600px;border: 1px solid #cccccc;box-shadow: 0 0 10px 3px #cccccc;margin-top: 150px;">
<form class="form-horizontal" name="form" ng-app="myApp" ng-controller="myCtrl" ng-submit="submitForm(form.$valid)" novalidate="novalidate">
<h2 class="col-sm-offset-2 col-sm-10">表单验证</h2>
<div class="form-group has-feedback" ng-class="{ 'has-error' : form.user.$invalid && form.user.$dirty || userValidate=='false' , 'has-success' : form.user.$valid && form.user.$dirty && (userValidate=='' || userValidate=='true') }">
<label for="user" class="col-sm-2 control-label">用户名:</label>
<div class="col-sm-5">
<input type="text" class="form-control" name="user" id="user" ng-model="user" ng-minlength="3" ng-maxlength="8" required="required" />
<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.user.$dirty && form.user.$valid && (userValidate=='' || userValidate=='true')" aria-hidden="true"></span>
<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.user.$dirty && form.user.$invalid || userValidate=='false'" aria-hidden="true"></span>
</div>
<span class="col-sm-5" ng-show="form.user.$dirty && form.user.$invalid">
<span class="help-block" ng-show="form.user.$error.required">用户名是必须的</span>
<span class="help-block" ng-show="form.user.$error.minlength">your name is too short!</span>
<span class="help-block" ng-show="form.user.$error.maxlength">your name is too long!</span>
</span>
<span class="col-sm-5" ng-show="form.user.$dirty && form.user.$valid">
<span class="help-block" ng-show="form.user.$valid && userValidate!='false'">OK</span>
<span class="help-block" ng-show="userValidate=='false'">用户名或密码错误</span>
</span>
</div>
<div class="form-group has-feedback" ng-class="{ 'has-error' : form.email.$invalid && form.email.$dirty , 'has-success' : form.email.$valid && form.email.$dirty }">
<label for="email" class="col-sm-2 control-label">邮箱:</label>
<div class="col-sm-5">
<input type="email" class="form-control" name="email" id="email" ng-model="email" required="required" />
<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.email.$dirty && form.email.$valid" aria-hidden="true"></span>
<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.email.$dirty && form.email.$invalid" aria-hidden="true"></span>
</div>
<span class="col-sm-5" ng-show="form.email.$dirty && form.email.$invalid">
<span class="help-block" ng-show="form.email.$error.required">邮箱是必须的</span>
<span class="help-block" ng-show="form.email.$error.email">邮箱地址非法</span>
</span>
<span class="col-sm-5" ng-show="form.email.$dirty && form.email.$valid">
<span class="help-block" ng-show="form.email.$valid">OK</span>
</span>
</div>
<div class="form-group has-feedback" ng-class="{ 'has-error' : form.phone.$invalid && form.phone.$dirty , 'has-success' : form.phone.$valid && form.phone.$dirty }">
<label for="phone" class="col-sm-2 control-label">手机号:</label>
<div class="col-sm-5">
<input type="tel" class="form-control" name="phone" id="phone" ng-pattern="regex" ng-model="phone" required="required" />
<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.phone.$dirty && form.phone.$valid" aria-hidden="true"></span>
<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.phone.$dirty && form.phone.$invalid" aria-hidden="true"></span>
</div>
<span class="col-sm-5" ng-show="form.phone.$dirty && form.phone.$invalid">
<span class="help-block" ng-show="form.phone.$error.required">手机号不能为空</span>
<span class="help-block" ng-show="form.phone.$error.pattern">请输入正确的11位手机号码</span>
</span>
<span class="col-sm-5" ng-show="form.phone.$dirty && form.phone.$valid">
<span class="help-block" ng-show="form.phone.$valid">OK</span>
</span>
</div>
<div class="form-group has-feedback" ng-class="{ 'has-error' : form.password.$invalid && form.password.$dirty || userValidate=='false' , 'has-success' : form.password.$valid && form.password.$dirty && (userValidate=='' || userValidate=='true') }">
<label for="password" class="col-sm-2 control-label">密码:</label>
<div class="col-sm-5">
<input type="password" class="form-control" name="password" id="password" ng-pattern="" ng-model="password" required="required" />
<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.password.$dirty && form.password.$valid && (userValidate=='' || userValidate=='true')" aria-hidden="true"></span>
<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.password.$dirty && form.password.$invalid || userValidate=='false'" aria-hidden="true"></span>
</div>
<span class="col-sm-5" ng-show="form.password.$dirty && form.password.$invalid">
<span class="help-block" ng-show="form.password.$error.required">密码不能为空</span>
<!--<span class="help-block" ng-show="form.password.$error.pattern">请输入正确的密码</span>-->
</span>
<span class="col-sm-5" ng-show="form.password.$dirty && form.password.$valid">
<span class="help-block" ng-show="form.password.$valid && userValidate!='false'">OK</span>
</span>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-primary" ng-click="validate()" value="submit" ng-disabled="form.user.$dirty && form.user.$invalid || form.email.$dirty && form.email.$invalid || form.phone.$dirty && form.phone.$invalid" />
<a href="test19_register.html" class="btn btn-warning" ng-click="register()">register</a>
</div>
</div>
<!--<span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>-->
</form>
</div>
<script type="text/javascript">
//要像这样加载模板和控制器验证才能有效
var app = angular.module('myApp', []);
app.config(function($httpProvider){
$httpProvider.defaults.transformRequest = function(obj){
var str = [];
for(var p in obj){
str.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));
}
return str.join("&");
}
$httpProvider.defaults.headers.post = {
'Content-Type' : 'application/x-www-form-urlencoded'
}
});
app.controller('myCtrl', function($scope,$http) {
$scope.regex = /^1[34578]\d{9}$/;
$scope.userValidate = '';
//验证用户名
$scope.validate = function(){
$http
.post('http://localhost/test19_validate.php',{name : $scope.user, email : $scope.email, tel : $scope.phone, password : $scope.password})
.then(function successCallback(response){
//用户名或密码错误
if(response.data == 'error'){
$scope.userValidate = 'false';
}else{
$scope.userValidate = 'true';
window.location = './test19_success.html';
}
},function errorCallback(response){
alert('验证失败');
});
}
});
</script>
</body>
</html>
test19_register.html //用户注册页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test19_用户注册页面</title>
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div class="container" style="width: 600px;border: 1px solid #cccccc;box-shadow: 0 0 10px 3px #cccccc;margin-top: 150px;">
<form class="form-horizontal" name="form" ng-app="myApp" ng-controller="myCtrl" ng-submit="submitForm(form.$valid)" novalidate="novalidate">
<h2 class="col-sm-offset-2 col-sm-10">表单验证</h2>
<div class="form-group has-feedback" ng-class="{ 'has-error' : form.user.$invalid && form.user.$dirty || rename , 'has-success' : form.user.$valid && form.user.$dirty && !rename }">
<label for="user" class="col-sm-2 control-label">用户名:</label>
<div class="col-sm-5">
<input type="text" class="form-control" name="user" id="user" ng-model="user" ng-minlength="3" ng-maxlength="8" required="required" />
<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.user.$dirty && form.user.$valid && !rename" aria-hidden="true"></span>
<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.user.$dirty && form.user.$invalid || rename" aria-hidden="true"></span>
</div>
<span class="col-sm-5" ng-show="form.user.$dirty && form.user.$invalid || rename">
<span class="help-block" ng-show="form.user.$error.required">用户名是必须的</span>
<span class="help-block" ng-show="form.user.$error.minlength">your name is too short!</span>
<span class="help-block" ng-show="form.user.$error.maxlength">your name is too long!</span>
<span class="help-block" ng-show="rename">用户名已存在</span>
</span>
<span class="col-sm-5" ng-show="form.user.$dirty && form.user.$valid">
<span class="help-block" ng-show="form.user.$valid && !rename">OK</span>
</span>
</div>
<div class="form-group has-feedback" ng-class="{ 'has-error' : form.email.$invalid && form.email.$dirty , 'has-success' : form.email.$valid && form.email.$dirty }">
<label for="email" class="col-sm-2 control-label">邮箱:</label>
<div class="col-sm-5">
<input type="email" class="form-control" name="email" id="email" ng-model="email" required="required" />
<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.email.$dirty && form.email.$valid" aria-hidden="true"></span>
<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.email.$dirty && form.email.$invalid" aria-hidden="true"></span>
</div>
<span class="col-sm-5" ng-show="form.email.$dirty && form.email.$invalid">
<span class="help-block" ng-show="form.email.$error.required">邮箱是必须的</span>
<span class="help-block" ng-show="form.email.$error.email">邮箱地址非法</span>
</span>
<span class="col-sm-5" ng-show="form.email.$dirty && form.email.$valid">
<span class="help-block" ng-show="form.email.$valid">OK</span>
</span>
</div>
<div class="form-group has-feedback" ng-class="{ 'has-error' : form.phone.$invalid && form.phone.$dirty , 'has-success' : form.phone.$valid && form.phone.$dirty }">
<label for="phone" class="col-sm-2 control-label">手机号:</label>
<div class="col-sm-5">
<input type="tel" class="form-control" name="phone" id="phone" ng-pattern="regex" ng-model="phone" required="required" />
<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.phone.$dirty && form.phone.$valid" aria-hidden="true"></span>
<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.phone.$dirty && form.phone.$invalid" aria-hidden="true"></span>
</div>
<span class="col-sm-5" ng-show="form.phone.$dirty && form.phone.$invalid">
<span class="help-block" ng-show="form.phone.$error.required">手机号不能为空</span>
<span class="help-block" ng-show="form.phone.$error.pattern">请输入正确的11位手机号码</span>
</span>
<span class="col-sm-5" ng-show="form.phone.$dirty && form.phone.$valid">
<span class="help-block" ng-show="form.phone.$valid">OK</span>
</span>
</div>
<div class="form-group has-feedback" ng-class="{ 'has-error' : form.password.$invalid && form.password.$dirty , 'has-success' : form.password.$valid && form.password.$dirty }">
<label for="password" class="col-sm-2 control-label">密码:</label>
<div class="col-sm-5">
<input type="password" class="form-control" name="password" id="password" ng-pattern="" ng-model="password" required="required" />
<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.password.$dirty && form.password.$valid" aria-hidden="true"></span>
<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.password.$dirty && form.password.$invalid" aria-hidden="true"></span>
</div>
<span class="col-sm-5" ng-show="form.password.$dirty && form.password.$invalid">
<span class="help-block" ng-show="form.password.$error.required">密码不能为空</span>
<!--<span class="help-block" ng-show="form.password.$error.pattern">请输入正确的密码</span>-->
</span>
<span class="col-sm-5" ng-show="form.password.$dirty && form.password.$valid">
<span class="help-block" ng-show="form.password.$valid">OK</span>
</span>
</div>
<div class="form-group has-feedback" ng-class="{ 'has-error' : form.confirmPassword.$invalid && form.confirmPassword.$dirty || (password!=confirmPassword && form.confirmPassword.$dirty) , 'has-success' : form.confirmPassword.$valid && form.confirmPassword.$dirty && password==confirmPassword }">
<label for="confirmPassword" class="col-sm-2 control-label">确认密码:</label>
<div class="col-sm-5">
<input type="password" class="form-control" name="confirmPassword" id="confirmPassword" ng-pattern="" ng-model="confirmPassword" required="required" />
<span class="glyphicon glyphicon-ok form-control-feedback" ng-show="form.confirmPassword.$dirty && form.confirmPassword.$valid && password==confirmPassword" aria-hidden="true"></span>
<span class="glyphicon glyphicon-remove form-control-feedback" ng-show="form.confirmPassword.$dirty && form.confirmPassword.$invalid || (password!=confirmPassword && form.confirmPassword.$dirty)" aria-hidden="true"></span>
</div>
<span class="col-sm-5" ng-show="form.confirmPassword.$dirty && form.confirmPassword.$invalid">
<span class="help-block" ng-show="form.confirmPassword.$error.required">密码不能为空</span>
</span>
<span class="col-sm-5" ng-show="form.confirmPassword.$dirty && form.confirmPassword.$valid">
<span class="help-block" ng-show="form.confirmPassword.$valid && password==confirmPassword">OK</span>
<span class="help-block" ng-show="password!=confirmPassword && form.confirmPassword.$dirty">两次密码不一致</span>
</span>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-primary" value="submit" ng-disabled="form.user.$dirty && form.user.$invalid || form.email.$dirty && form.email.$invalid || form.phone.$dirty && form.phone.$invalid || form.password.$dirty && form.password.$invalid || form.confirmPassword.$dirty && form.confirmPassword.$invalid || confirmPassword!=password" />
</div>
</div>
<!--<span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>-->
</form>
</div>
<script type="text/javascript">
//要像这样加载模板和控制器验证才能有效
var app = angular.module('myApp', []);
app.config(function($httpProvider){
$httpProvider.defaults.transformRequest = function(obj){
var str = [];
for(var p in obj){
str.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));
}
return str.join("&");
}
$httpProvider.defaults.headers.post = {
'Content-Type' : 'application/x-www-form-urlencoded'
}
});
app.controller('myCtrl', function($scope , $http) {
$scope.regex = /^1[34578]\d{9}$/;
$scope.rename = false;
//表单提交
$scope.submitForm = function(isValid) {
if(isValid) {
$http
.post('http://localhost/test19_register.php?m=add',{name : $scope.user, email : $scope.email, tel : $scope.phone, password : $scope.password})
.then(function successCallback(response){
if(response.data == '此用户名已被注册'){
//用户名已存在
$scope.rename = true;
}else{
//注册成功
alert(response.data);
window.location = './test19.html';
}
},function errorCallback(response){
alert(response.data);
});
}
}
});
</script>
</body>
</html>
test19_validate.php
<?php
/*一定要加上这两个header*/
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Content-Type:text/html;charset=utf-8");
$connect = mysqli_connect('localhost','root','root','angular') or die('Unale to connect');
//用户登录验证
$post = [];
$formData = [];
$data = file_get_contents("php://input");
$data = explode('&',$data);
foreach ($data as $k => $v){
$post[] = explode('=',$v);
}
foreach ($post as $k => $v){
$formData += [$v[0] => urldecode($v[1])];
}
$name = $formData['name'];
$email = $formData['email'];
$tel = $formData['tel'];
$password = $formData['password'];
$password = md5($password);
$sql = "SELECT * FROM user WHERE name='$name' AND password='$password'";
$result = mysqli_query($connect,$sql);
$row = mysqli_fetch_assoc($result);
if($row){
echo 'success';
}else{
echo 'error';
}
?>
test19_register.php
<?php
/*一定要加上这两个header*/
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Content-Type:text/html;charset=utf-8");
$connect = mysqli_connect('localhost','root','root','angular') or die('Unale to connect');
//用户注册
if($_GET['m'] == 'add'){
$post = [];
$formData = [];
$data = file_get_contents("php://input");
$data = explode('&',$data);
foreach ($data as $k => $v){
$post[] = explode('=',$v);
}
foreach ($post as $k => $v){
$formData += [$v[0] => urldecode($v[1])];
}
$name = $formData['name'];
//不能有相同的用户名
$sql = "SELECT * FROM user WHERE name='$name'";
$result = mysqli_query($connect,$sql);
//$row为找到的满足条件的一条条记录
$row = mysqli_fetch_assoc($result);
if($row){
//若有相同的用户名已注册
echo '此用户名已被注册';
die;
}
$email = $formData['email'];
$tel = $formData['tel'];
$password = $formData['password'];
$password = md5($password);
$sql = "INSERT INTO user(name,email,tel,password) VALUES ('$name', '$email', '$tel', '$password')";
$result = mysqli_query($connect,$sql);
if($result){
echo '用户注册成功,请重新登录';
}else{
echo '注册失败';
}
}
?>
(写这两个php文件的时候偷了下懒,只是粗略的实现了自己想要的功能)
其中验证部分,因为使用的是BootStrap,配合Angular实现的效果个人还是蛮喜欢的,验证除了要写的正则表达式外(好像还没有加上...),在控制器中基本上是没有代码的;这里补充几个Angular中表单的状态:
$dirty 表单有填写记录
$valid 字段内容合法的
$invalid 字段内容是非法的
$pristine 表单没有填写记录
$error 包含该验证字段的错误信息,像 required,minlength,maxlength等等;
其实写这个用户登录注册,主要是想熟悉了解Angular中对数据库的操作,$http;
(以下是个人对Angular操作数据库的理解,肯定是还有很多问题的,望大牛们多多指点0.0)
var app = angular.module('myApp', []); //定义应用类
app.controller('myCtrl', function($scope,$http) {}); //定义控制器
(若要使用$http这个服务,记得一定要事先引用它哦)
要解释$http服务前,我想先谈谈我对$scope的理解:
$scope是一个把view(一个DOM元素)连结到controller上的对象, $scope 实际上就是一个JavaScript对象; 每一个Angular应用都会有一个 $rootScope。这个 $rootScope 是最顶级的scope,它对应着含有 ng-app 指令属性的那个DOM元素。 要明确创建一个$scope 对象,我们就要给DOM元素安上一个controller对象,使用的是ng-controller 指令属性; ng-model指令属性 被用来将DOM文本输入框的值,跟controller里的$scope model绑定起来。具体的实现过程,是在这个值上绑定了一个$watch函数(类似JavaScript里的事件监听函数)。
接下来是$http
操作数据库之前,通常需要在前端和数据库之间编写一层“Web服务”。 AngularJS应用程序会向你的Web服务发出请求。 你的Web服务将与MySQL进行通信,以检查用户权限,读取数据或写入数据。这些后端Web服务可以用任何语言和框架来编写。
首先,$http中有两个常用的请求get和post方法;分别有两个写法:
1.$http.get('test.php',{});
2.$http({
method : 'get',
url : 'test.php',
params : {
'username' : 'lzc'
}
});
由于增删改都需要由html页面传递数据到后台php文件中,但是像$http.post('test.php' , {id : 1});这样传递,在php文件中用$_POST是获取不到传递过来的数据的。So...
angular中$http模块POST请求request pay load转form data的两种方法:
var app = angular.module('app',[]);
//angular中$http模块POST请求request pay load转form data的两种方法
//打开浏览器的调试工具,会在Network中看到这些信息
//方法一
app.config(function($httpProvider){
$httpProvider.defaults.transformRequest = function(obj){
var str = [];
for(var p in obj){
str.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));
}
return str.join("&");
}
$httpProvider.defaults.headers.post = {
'Content-Type' : 'application/x-www-form-urlencoded'
}
});
//方法二
app.controller('ctrl',function($scope,$http){
$http({
method : 'post',
url : 'http://localhost/test20.php',
data : {name : 'lzc' , age : 20},
headers : {'Content-Type':'application/x-www-form-urlencoded'},
transformRequest:function(obj){
var str = [];
for(var p in obj){
str.push(encodeURIComponent(p)+"="+encodeURIComponent(obj[p]));
}
return str.join("&");
}
}).then(function successCallback(response){
alert('s');
},function errorCallback(response){
alert('er');
});
});
php文件:
<?php
/*一定要加上这两个header*/
header("Access-Control-Allow-Origin: *");
// header("Content-Type: application/json; charset=UTF-8");
header("Content-Type:text/html;charset=utf-8");
$post = [];
$formData = [];
$data = file_get_contents("php://input");
$data = explode('&',$data);
foreach ($data as $k => $v){
$post[] = explode('=',$v);
}
foreach ($post as $k => $v){
$formData += [$v[0] => urldecode($v[1])];
}
$name = $formData['name'];
$quantity = $formData['quantity'];
$price = $formData['price'];
$connect = mysqli_connect('localhost','root','root','angular') or die('Unale to connect');
$sql = "insert into shop (name,quantity,price) values('$name','$quantity','$price')";
$result = mysqli_query($connect,$sql);
if($result){
echo 'success';
}else{
echo 'error';
}
?>
至此总得就写完啦,第一次肯定会有很多问题,欢迎大家指出不足的问题。
网友评论