Skip to content
This repository has been archived by the owner on Jul 1, 2020. It is now read-only.

Regular Expression Pattern

Ghislain B edited this page Mar 23, 2017 · 39 revisions

Since version 1.3.35

With Angular-Validation you can also use Custom Regular Expression Patterns, there is no limitation on the Validator itself and you can even use the pipe " | " inside the regular expression without being scared of interfering with the other validation filters. The only thing required, is to prefix the Validator with pattern= and then add your regular expression pattern and finally at the end use the :alt= to provide an Alternate Text for showing your custom error message.

There is also no need to escape anything, just use regular expression and you're good to go. So in resume, the syntax would look like this pattern=/.../:alt=Your error message

Examples

Directive
<!-- let's define a quick pattern for testing date code (YYWW) -->
<input type="text" name="datecode" 
    validation="pattern=/^(0[9]|1[0-9]|2[0-9]|3[0-9])(5[0-2]|[0-4][0-9])$/:alt=Pattern must be YYWW" />

<!-- you can mix it with other validators -->
<input type="text" name="datecode" 
    validation="alpha|exact_len:4|pattern=/^(0[9]|1[0-9]|2[0-9]|3[0-9])(5[0-2]|[0-4][0-9])$/:alt=Pattern must be YYWW|required" />

<!-- another sweet example, a person's full name (first+last name) -->
<input type="text" name="fullname"
    validation="alpha_dash_spaces|pattern=/(\w+)\s(\w+)/:alt=Provide your full name|required" />
Service

Same thing but your validator rules are defined in the controller

// inject the ValidationService inside your Controller
myApp.controller('Ctrl', function ($scope, ValidationService) {
  // start by creating the service
  var myValidation = new ValidationService();

  // full definition
  myValidation.addValidator({
    elmName: 'datecode',
    scope: $scope,
    rules: 'pattern=/^(0[9]|1[0-9]|2[0-9]|3[0-9])(5[0-2]|[0-4][0-9])$/:alt=Pattern must be YYWW|required'
  });

  // or defined as 1 liner
  myValidation
    .addValidator('datecode', 'pattern=/^(0[9]|1[0-9]|2[0-9]|3[0-9])(5[0-2]|[0-4][0-9])$/:alt=Pattern must be YYWW|required');
    .addValidator('fullname', 'pattern=/(\w+)\s(\w+)/:alt=Provide your full name|required');
});

Test your Pattern before adding it to Angular-Validation

Make sure they work before adding them as a validation

// pattern accepting 2 words separated by a space (example a person full name)
var pattern = /(\w+)\s(\w+)/;
var result1 = pattern.test("John Smith");   // will return True
var result2 = pattern.test("JohnSmith");    // will return False
Add it as a validation

Alright we tested it, let's use it

<input type="text" name="fullname" 
    validation="pattern=/(\w+)\s(\w+)/:alt=You must provide your full name|required" />

Error Message displaying

In the introduction, I told you to use the :alt for providing the error message, but in reality there is actually 2 ways of providing the message. The Alternate Text with :alt is the preferred and most common option (which is why I mentioned it in the introduction). The second option is through generic locale error message.

  1. Alternate Text (preferred option)

    As described in previous examples, you would use it like this

    pattern=/.../:alt=Your error message
  2. Generic Locale Error Message

    Similar to all the other Validators, it uses a generic locale translation (coming from the Angular-Translate locales translation JSON files) for displaying the error message. Generic because it's a default message, which is Must be following this format: {{ yourFormat }}, but to use it is a little harder, you need to provide an extra variable to pass the format and it's different in both the Directive and Service. The funny thing is that we still need the alt: to use it anyway. See the example below: ######Directive The directive needs to add an extra variable, in our case named translationData, passed as an argument to the translate function. And then you need to fill that variable inside your Controller. For example:

<!-- Example of a MAC address -->
<!-- let's define a quick pattern for testing date code (YYWW) -->
<input type="text" name="mac" 
   validation="pattern=/^[0-9A-F]{12}$/:alt={{ 'INVALID_PATTERN_DATA' | translate:translationData }}|required"
myApp.controller('Ctrl', function ($scope) {
        // if we want to use the invalid_pattern_data locale translation as an alternateText (:alt=)
        // then we need to supply an extra 'data' variable (as defined in the JSON locale) of what we expect the search pattern on our input4
        $scope.translationData = { data: 'Hexadecimal' };
    });
Service

As for the Service, we could write it on 1 line of code.

    // inject the ValidationService inside your Controller
    myApp.controller('Ctrl', function ($scope, ValidationService) {
        // start by creating the service
        var myValidation = new ValidationService();
        myValidation.addValidator('mac', 'pattern=/^[0-9A-F]{12}$/:alt=' + $translate.instant('INVALID_PATTERN_DATA', { data: 'Hexadecimal' }) + '|required');
    });

As you can see, using the option(2) is not as easy as the option(1), but it's still an option. It could be useful in some cases, for example, I use it myself in my Live Plunker Demo on the input4 of both the Directive and Service. The reason being that I want a fixed and generic message for my Protractor tests.

Important Notice (on previous implementation)

regex: ... :regex is Deprecated

Previous (regex) implementation of regex: ... :regex has been deprecated but is still part of Angular-Validation, so don't be afraid as it won't break your code, even if you keep the old implementation (both implementations old/new works).

Why?

The usage of it was different and was requesting a few things: required to escape everything, required providing an error message directly inside the validator and finally was not close enough (to my taste) to regular expression. Since I also created the :alt= (alternate text) later in the development of the library, it also make sense to use it, so that it follows a much more concise standard.

Suggestion

So I strongly suggest you to update your code and use the new pattern= validator, you will gain in term of how easy it is to add custom regular expression... but don't being afraid break changes, your code does still works with the old implementation. It's just a suggestion ;)

Clone this wiki locally