Reputation: 27
I am writing a simple form, where I want to save the form result into an array, having both the first name and last name updated, if either or both fields are left empty it should throw an alert message. And the array should not store empty values and I wanted to handle this on the client side. I am kind of confused on how to keep a check on the input values before storing them. Here is the code snippet: https://jsbin.com/guduwakeji/edit?html,js,output
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.ele = [];
$scope.updateDetails = function(ele) {
if (!ele.firstname && !ele.lastname) {
alert("Ele cannot be empty");
} else {
ele.push({
'firstname': '',
'lastname': ''
});
alert(ele.firstname + " " + ele.lastname);
}
console.log(ele);
};
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body ng-app="myApp">
<div ng-controller="formCtrl">
<div>
First Name:
<input type="text" ng-model="ele.firstname">
</br>
Last Name:
<input type="text" ng-model="ele.lastname">
<br/>
<input type="button" value="Submit" ng-click="updateDetails(ele)">
</div>
</div>
</body>
</html>
Upvotes: 1
Views: 84
Reputation: 3531
use this code
i figure out this way to validate your form
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.ele={};
$scope.updateDetails = function(ele){
if(ele.firstname && ele.lastname)
{ console.log(ele);}
else{
alert("empty field not allowed");
}
};
});
Upvotes: 1