angularjsangularjs-ng-modelangularjs-validation

How can I validate keyup function in AngularJS


Here I'm using web API with AngularJS here I'm trying to if my keyup function is not valid then its shows me please select another email.

 public IHttpActionResult GetEailCount(string email)
        {
         int obj= objrepo.countEmployee(email);
         if (obj == 1)
             return Ok("Email already exist please check another...");
         else
             return Content(HttpStatusCode.Accepted, "Email available..");
        }

AngularJS:

<input type="text" name="emailtxt" ng-model="emailsId" ngkeyup="Getvaliedemail(emailsId)" required /> 
        <span class="help-block" ng-show="(f1.emailtxt.Getvaliedemail.$valid)">Email exist</span>

Here how can I display Error msg based on my code

 $scope.Getvaliedemail = function (someval) {

        if (someval.length > 3) {
            Empfac.Employemail(someval).then(function (d) {
                $q.resolve(d);
            }).catch(function (xhr) {
                $q.reject(xhr);
            })
        }
    }

})
 EmployeeFactory.Employemail = function (mail) {
            debugger;
            alert()
            return $http({
                url: 'http://localhost:63252/Api/Home/GetEailCount/' + mail,
                mathod: 'GET',
                headers: {
                    "Content-Type": "application/json"
                },
                data: mail
            })
        }

Solution

  • You have to use $asyncValidators for this using a directive.

    var app = angular.module("sa", []);
    
    app.factory('EmployeeFactory', function ($http) {
        var obj = {};
        obj.Employemail = function (mail) {
            return $http({
                url: 'http://localhost:63252/Api/Home/GetEailCount/' + mail,
                mathod: 'GET',
                headers: {
                    "Content-Type": "application/json"
                },
                data: mail
            })
        };
    
        return obj;
    });
    
    app.directive('validateEmailFoo', function($q, EmployeeFactory) {
        return {
            require: 'ngModel',
            retrict: 'A',
            link: function ($scope, $element, $attr, ngModelCtrl) {
                ngModelCtrl.$asyncValidators.Getvaliedemail = function (modelValue, viewValue) {
                    var someval = modelValue || viewValue;
    
                    var deferred = $q.defer();
    
                    EmployeeFactory.Employemail(someval).then(function (d) {
                        if (d.status == 202) {
                            deferred.resolve(d);        // validation passes
                        } else if (d.status == 200) {
                            deferred.reject(xhr);       // validation fails
                        }
                    }).catch(function (xhr) {
                        deferred.reject(xhr);       // validation fails
                    })
    
                    return deferred.promise;
                };
            }
        };
    });
    
    app.controller("FooController", function ($scope) {
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
    
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    
    
    <div ng-app="sa" ng-controller="FooController">
      <form name="f1">
        <input type="text" name="emailtxt" ng-model="emailsId" required validate-email-foo /> 
        <span class="help-block" ng-show="f1.emailtxt.$error.Getvaliedemail">Email exist</span>
      </form>
    </div>

    Pay attention to ng-show="f1.emailtxt.$error.Getvaliedemail".

    Remember, I'm assuming, your server will respond with 202 status code means email does not exist and 200 status code means email exists.

    The code here will always fail the validation because the localhost URL is invalid and hence the rejection. Try with some real time server