d_unknown d_unknown - 5 months ago 50
AngularJS Question

validating data in database in angularjs

I am using angularjs in my project. In a process/module, the form will not be submitted if a certain data input is already exist in the database. For example, this process: registering /Signing up. If the user inputted a username that's already been used by someone, the form will not be submitted. And it will be checked in a controller where the list of usernames has been loaded prior to user entering the data by comparing (in a for loop). My question is, is this a good way of checking the data or do I have to use $http?

Edit:

<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group"><label class="control-label">Username</label>
<input type="text" ng-model="reg.username" usernameAvailable
name="username" class="form-control input-md"
placeholder="Username" required />
<div ng-if="regForm.$pending.usernameExists">checking....</div>
<div ng-if="regForm.$error.usernameExists">username exists
already
</div>
</div>
</div>

mainApp.directive('usernameAvailable', function($timeout, $q, $http) {
return {
restrict: 'AE',
require: 'ngModel',
link: function(scope, elm, attr, model) {
model.$asyncValidators.usernameExists = function() {
//here you should access the backend, to check if username exists
//and return a promise
// var defer = $q.defer();
// $timeout(function(){
// model.$setValidity('usernameExists', true);
// defer.resolve;
// }, 1000);
// return defer.promise;
console.log(model);
return $http.get(BASE_URL+'Register/validate?u='+username).
then(function(res){+$timeout(function(){
model.$setValidity('usernameExists', !!res.data);
}, 1000);
});
};
}
}
});


Php controller:

public function validate(){


$this->load->model('account_model');
$data =$this->account_model->exist($this->input->get('u'));
echo json_encode($data);
}

Answer

You should take the data to the server. And there, should fire a query in db to check if this data already exists. If it does then show error message on UI and do not save other wise save it with success message.

Fire query (sample) Something like :

 SELECT * FROM users WHERE username='myName'

If records are more than 0, then what you have is a repeated value.

Do not fetch all the records on UI and then loop through them.

Think of :

  1. What if there are 1 Million or more records?
  2. Security ? (You are getting all the user names to client)

And other such things.

Hope it guides you.