d_unknown d_unknown - 1 year ago 121
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?


<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

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;
return $http.get(BASE_URL+'Register/validate?u='+username).
model.$setValidity('usernameExists', !!res.data);
}, 1000);

Php controller:

public function validate(){

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


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.