Url Validation. Ng-pattern Not Working
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 requir
Solution 1:
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?
.
Solution 2:
can try by using new RegExp
newRegExp(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');
Post a Comment for "Url Validation. Ng-pattern Not Working"