Why is Angularjs ng-pattern not working with the following regexp?

前端 未结 3 1805
独厮守ぢ
独厮守ぢ 2020-12-16 14:17

For some reason the initialized value doesn\'t appear in the field, but the second field without the ng-pattern does work. any ideas?

    angular.module(\'ap         


        
相关标签:
3条回答
  • 2020-12-16 14:50

    I too was facing same problem. Found a workaround to do this.

    You have to do something like this in your controller.

    $scope.myRegex = /[a-zA-Z]{4}[0-9]{6,6}[a-zA-Z0-9]{3}/; (don't put expression in quotes)

    Finally

    <input ng-model="widget.title" required ng-pattern="myRegex">

    It will now be working.

    0 讨论(0)
  • 2020-12-16 15:14

    UPDATE

    I looked into it a bit (never really used Angular), and by using the name attribute on the form and inputs, you can grab an error like shown in my newest JSFiddle. Its in the format: {{formName.inputName.$error}}. This returns an object with parameters that equal a boolean. So {{form.title.$error.pattern}} will be true when there is an error with the regular expression (so you would display the error). I also cleaned (works the same) your regex to: /^[A-Z]{4}\d{6}[A-Z\d]{3}$/i.


    OLD

    The ng-pattern attribute attempts to match the field based on this regular expression: /[a-zA-Z]{4}[0-9]{6,6}[a-zA-Z0-9]{3}/. This translates to 4 alphabetical characters, 6 digits, and 3 alphanumeric characters. Once you have a matching pattern, it will show up.

    You should be able to remove the ng-pattern attribute or change the expression to be less specific. For example, this JSFiddle will accept any value as long as the entire string is alphanumeric. Update the question if you want help with a different pattern.

    0 讨论(0)
  • 2020-12-16 15:14

    Yes indeed! This was causing me an issue to...leaving the quotes out is what fixed it for me.

     $scope.regVal= /([A-Z]{3}\s?(\d{3}|\d{2}|d{1})\s?[A-Z])|([A-Z]\s?(\d{3}|\d{2}|\d{1})\s?[A-Z]{3})|(([A-HK-PRSVWY][A-HJ-PR-Y])\s?([0][2-9]|[1-9][0-9])\s?[A-HJ-PR-Z]{3})/;
    
    0 讨论(0)
提交回复
热议问题