Question

I was using remote method of Jquery for checking if the username already exists, but I want to validate it using Angular js. The code for validation using Jquery is

 $("#registration-form").validate({
    rules: {
           'username': {
            required: true,
            minlength: 3,
            maxlength: 20,
            alphanumeric: true,
            remote: "/users/checkusername"
        },
     }
   });

I am new to Angular js. Any relevant link would be helpful.

Was it helpful?

Solution

HTML

<input type="text" name="username" ng-model="username" 
ng-pattern="/^[a-zA-Z0-9]{4,10}$/" ng-unique="tableDB.userDBField" />

AngularJS

directive('ngUnique', ['$http', function (async) {
  return {
    require: 'ngModel',
    link: function (scope, elem, attrs, ctrl) {
      elem.on('blur', function (evt) {
        scope.$apply(function () {
      var val = elem.val();
      var req = { "username":val, "dbField":attrs.ngUnique }
      var ajaxConfiguration = { method: 'POST', url: 'backendServices/checkUsername.php', data: req };
      async(ajaxConfiguration)
        .success(function(data, status, headers, config) {
          ctrl.$setValidity('unique', data.status);
            });
          });
        });
      }
    }
  }
]);

Check the full document Form Validation: The AngularJS Way

OTHER TIPS

I created a bridge between AngularJS and the jQuery Validation Plugin. It gives you the ability to define your validation options (rules, messages, etc.) inside your controller, so you don't have to create a new directive for each form or rule.

Give it a try: https://github.com/jpkleemans/angular-validate. Feedback is highly appreciated!

The following url will give you a step by step guide for form vaildation using angular, dont have to use JQuery at all.

http://scotch.io/tutorials/javascript/angularjs-form-validation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top