2

$scope.regex = '^((http|https|ftp):\/\/)?([a-z]+\.)?[a-z0-9-]+(\.[a-z]{1,4}){1,2}(/.*\?.*)?$';

This is the regular expression i'm using to validate url, and its working fine. I have checked it on AngularJS website.
<div class="field_input">
  <div style="width: 100%;">
    <input type="text" name="website" ng-model="custom.websites" placeholder="www.daiict.ac.in" ng-minlength=3 ng-pattern="regex" required/>
  </div>
</div>
<div class="valid-chk" ng-show="requestForm1.website.$dirty" style="margin-top: 5px;">
  <i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[requestForm1.website.$valid]" class="icon-correct"></i>
</div>

This is html snippet where the i'm trying to validate the input field. However this is not working. Also when I used ng-pattern all other validations on input field, except required, are also not working. Any idea why...

G. Hamaide
  • 7,078
  • 2
  • 36
  • 57
Dreamer
  • 73
  • 1
  • 10

2 Answers2

10

Your ng-pattern="regex" contains a string regex as its value. In order to refer to the real variable $scope.regex, you need to use the template syntax:

ng-pattern="{{regex}}"

Also, since the pattern is defined using a string you need to double escape the backslashes (see a similar example code at the ngPattern reference page):

$scope.regex = '^((https?|ftp)://)?([A-Za-z]+\\.)?[A-Za-z0-9-]+(\\.[a-zA-Z]{1,4}){1,2}(/.*\\?.*)?$';

Or just place them into a character class to avoid any ambiguity:

$scope.regex = '^((https?|ftp)://)?([a-z]+[.])?[a-z0-9-]+([.][a-z]{1,4}){1,2}(/.*[?].*)?$';

Or even pass the RegExp object since that way you can use the case-insensitive flag:

$scope.regex = "/^((https?|ftp):\\/\\/)?([a-z]+[.])?[a-z0-9-]+([.][a-z]{1,4}){1,2}(\\/.*[?].*)?$/i";

Alternatively, the same expression as above can be defined with a RegExp constructor:

$scope.regex = RegExp('^((https?|ftp)://)?([a-z]+[.])?[a-z0-9-]+([.][a-z]{1,4}){1,2}(/.*[?].*)?$', 'i');

I also suggest shortening http|https to https?.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

can try by using new RegExp

new RegExp(pattern, option)

I used i as option to ignore case

$scope.regex = $scope.regex = new RegExp('^((https?|ftp)://)?([a-z]+[.])?[a-z0-9-]+([.][a-z]{1,4}){1,2}(/.*[?].*)?$', 'i');

PLUNKER DEMO

Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68