我需要使用angularjs设计一个表单。我需要使用两种验证,
当用户填写表单时,我需要在飞行中验证该字段。默认情况下这是。
我不想禁用提交按钮。让我们说如果用户来到页面并直接点击提交按钮, 那么我也希望在不同领域显示所有错误。如何做到这一点。我尝试过使用$ setValidity()但是没有成功。如何做到这一点。
这是表格。
var sampleApp = angular.module("sampleApp", []);
sampleApp.controller('sampleCtrl', ['$scope', '$http', '$timeout',
function($scope, $http, $timeout) {
$scope.userData = {
fname: "",
lname: ""
};
$scope.submitted = false;
$scope.submitForm = function(registrationForm) {
$scope.registrationForm.fname.$dirty = true;
$scope.registrationForm.lname.$dirty = true;
if (registrationForm.$invalid) {
alert("form validation error.");
return;
} else {
alert("form submitted successfully.");
}
}
}
]);
input.ng-invalid {
border: 1px solid red;
}
input.ng-valid {
border: 1px solid green;
}
input.ng-pristine {
border-color: #FFFF00;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<script src="script.js"></script>
<html ng-app="sampleApp">
<body ng-controller="sampleCtrl">
<form name="registrationForm" ng-submit="submitForm(registrationForm)" novalidate>
FirstName*
<br>
<input type="text" name="fname" ng-model="userData.fname" required>
<span ng-show="registrationForm.fname.$dirty && registrationForm.fname.$error.required">
First name is required.
</span>
<br>LastName*
<br>
<input type="text" name="lname" ng-model="userData.lname" required>
<span ng-show="registrationForm.lname.$dirty && registrationForm.lname.$error.required">
Last name is required.
</span>
<br>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
答案 0 :(得分:1)
表单提交时,您可以轻松地进行表单验证,只需在$scope.registrationForm.lname.$dirty = true;
函数中设置$scope.registrationForm.fname.$dirty = true;
和$scope.submitForm
即可。
解决方案:
var sampleApp = angular.module("sampleApp", []);
sampleApp.controller('sampleCtrl', ['$scope', '$http', '$timeout',
function($scope, $http, $timeout) {
$scope.userData = {
fname: "",
lname: ""
};
$scope.submitted = false;
$scope.submitForm = function(registrationForm) {
if (registrationForm.$invalid) {
alert("form validation error.");
$scope.registrationForm.lname.$dirty = true;
$scope.registrationForm.fname.$dirty = true;
return;
} else {
alert("form submitted successfully.");
}
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<script src="script.js"></script>
<html ng-app="sampleApp">
<body ng-controller="sampleCtrl">
<form name="registrationForm" ng-submit="submitForm(registrationForm)" novalidate>
FirstName*
<br>
<input type="text" name="fname" ng-model="userData.fname" required>
<span ng-show="registrationForm.fname.$dirty && registrationForm.fname.$error.required">First name is required.</span>
<br>LastName*
<br>
<input type="text" name="lname" ng-model="userData.lname" required>
<span ng-show="registrationForm.lname.$dirty && registrationForm.lname.$error.required">Last name is required.</span>
<br>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>