Angularjs mail validation

In AngularJS, you can validate email addresses using various techniques. Here are a few approaches:

  1. Using a regular expression:

You can use a regular expression to validate the email address. Here's an example:

<input type="email" ng-model="email" required email-validator>

<script>
  angular.module('app').controller('Ctrl', function($scope) {
    $scope.emailValidator = function(email) {
      var re = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      return re.test(email);
    };
  });
</script>

In this example, the email-validator directive is used to validate the email address. The regular expression checks for the following:

  1. Using a library:

You can use a library like angular-email-validator to validate email addresses. This library provides a simple way to validate email addresses using a regular expression.

Here's an example:

<input type="email" ng-model="email" required email-validator>

<script>
  angular.module('app').controller('Ctrl', function($scope) {
    $scope.email = '';
  });
</script>

In this example, the email-validator directive is used to validate the email address. The library will automatically validate the email address using a regular expression.

  1. Using a custom directive:

You can create a custom directive to validate email addresses. Here's an example:

<input type="email" ng-model="email" required email-validator>

<script>
  angular.module('app').directive('emailValidator', function() {
    return {
      restrict: 'A',
      link: function(scope, element, attrs) {
        element.on('input', function() {
          var email = element.val();
          var re = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
          if (!re.test(email)) {
            element.addClass('error');
          } else {
            element.removeClass('error');
          }
        });
      }
    };
  });
</script>

In this example, the email-validator directive is used to validate the email address. The directive uses a regular expression to validate the email address and adds or removes the error class from the input element based on the validation result.

  1. Using a third-party library:

You can use a third-party library like angular-validator to validate email addresses. This library provides a simple way to validate email addresses using a regular expression.

Here's an example:

<input type="email" ng-model="email" required validator="email">

<script>
  angular.module('app').controller('Ctrl', function($scope) {
    $scope.email = '';
  });
</script>

In this example, the validator directive is used to validate the email address. The library will automatically validate the email address using a regular expression.

These are a few examples of how you can validate email addresses in AngularJS. You can choose the approach that best fits your needs.