Lee Lee
Lee Lee

Reputation: 583

Display error label besides the textbox if the user exists angularjs

I have a registration form with the textbox username. I want to do is when the entered username is exist, there is a label beside the textbox displaying "username exist" without clicking the submit button. What I've done so far is : http://jsfiddle.net/DharkRoses/s2qe3omh/2/ Any help would be much appreciated.

sample of my code:

<div ng-app="myApp" ng-controller="check">
<div class = "container">
    <h3>Registration form</h3>    
      <form name = "myForm">
             <label>Username:</label>
                <input type = "text" id = "user" ng-model="username"></input>
             <div class="msg-block" ng-show="myForm.$error"> <span class="msg-error" ng-show="myForm.user.$error.user">User exists.</span> 
     </form>
    <button ng-click = "userExists(username)">Submit</button>

Upvotes: 0

Views: 622

Answers (2)

Janaki Sathiyamurthy
Janaki Sathiyamurthy

Reputation: 588

Instead of calling the function submit button use it in the input box (use ng-blur or ng-change as per your requirement).

    <input type = "text" id= "user" ng-model="username" ng-blur="userExists(userName)"></input>
    <div ng-if="existingUser">User already exists !!!</div>

In your function,

$scope.userExists = function(username){
            if($scope.users.indexOf(userName) > 0){
                $scope.existingUser=true;
            }else {
                $scope.existingUser=false;
            }
        };

You can display error message based on the value on existingUser variable

Upvotes: 1

Deblaton Jean-Philippe
Deblaton Jean-Philippe

Reputation: 11388

You need an array of users on your client (and as far as security is concerned, this is not good practice).

   var app = angular.module("myApp", []);
    app.controller('check', function ($scope) {

        $resource('someUrl').query({}, function(users){
             $scope.users = users;  //users is : ["foo", "bar", "admin", ...]
        }, function (error){
             //handle error here
        });

        $scope.userExists = function(username){
            if($scope.users.indexOf(userName) > 0){
                alert("user exists!");
            }else {
                alert("save");
            }
        };


    });

Upvotes: 1

Related Questions