How to create a directive that validates input fields based on regex patterns

0 votes
Can i know How to create a directive that validates input fields based on regex patterns?
4 days ago in Node-js by Nidhi
• 14,600 points
29 views

1 answer to this question.

0 votes

You can define a custom directive that uses ngModelController for validation.

AngularJS Custom Directive with Regex Validation

app.directive('regexValidator', function() {

  return {

    require: 'ngModel',

    scope: {

      pattern: '@regexValidator'

    },

    link: function(scope, element, attrs, ngModel) {

      ngModel.$validators.regex = function(modelValue, viewValue) {

        var value = modelValue || viewValue;

        var regex = new RegExp(scope.pattern);

        return regex.test(value);

      };

    }

  };

});

HTML:

<input type="text" name="email" ng-model="user.email" regex-validator="^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" required />

<span ng-show="form.email.$error.regex">Invalid email format!</span>

answered 2 days ago by anonymous

Related Questions In Node-js

0 votes
0 answers

How to create a responsive navbar that collapses on smaller screens in Bootstrap 3?

With the help of proper code example ...READ MORE

Apr 1 in Node-js by Nidhi
• 14,600 points
37 views
0 votes
1 answer
0 votes
1 answer

How to create a Functional Component that returns a greeting?

To create a Functional Component that returns ...READ MORE

answered Mar 21 in Node-js by Dua
99 views
0 votes
1 answer

How to handle the swiperight event to trigger custom actions in jQuery Mobile?

To handle the swiperight event and trigger ...READ MORE

answered 2 days ago in Node-js by anonymous
28 views
0 votes
1 answer

How to implement a directive that auto-saves form data periodically?

To create a directive that automatically saves ...READ MORE

answered 2 days ago in Node-js by anonymous
28 views
0 votes
1 answer

How to dynamically inject components into the DOM using @Component?

You need to use ComponentFactoryResolver and ViewContainerRef. ...READ MORE

answered 2 days ago in Node-js by anonymous
39 views
0 votes
1 answer

How to use host bindings to bind properties to the host element in a component?

In Angular (2+), the @HostBinding() decorator allows ...READ MORE

answered 2 days ago in Node-js by anonymous
39 views
0 votes
1 answer

How to develop a directive that restricts user input based on custom conditions?

To create an Angular directive that restricts ...READ MORE

answered 2 days ago in Node-js by anonymous
31 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP