4

I am trying to achieve field validation with angular reactive forms with regex pattern ##.##.##.##. For some patterns, it is not working. I tried the below input 12.25.36.25 which fails the validation, tested the pattern (^\d{2}.\d{2}.\d{2}.\d{2}$) with regextester which works fine. I am not sure the what's going wrong here. Any help is much appreciated.

Here is the StackBlitz.

1 Answer 1

1

The reason is you forgot to add a field in class question-base called pattern. Here is the code:

export class QuestionBase<T> {
  ...
  pattern: string;

  constructor(options: {
      ...
      pattern?: string
    } = {}) {
    ...
    this.pattern = options.pattern || null
  }
}

Another problem is that ##.##.##.## is not a valid number. You need to change that input to be of type text. Lastly if your pattern is a regular expression you need to use javascript's regex type instead of string. Replace your pattern to be /^\d{2}.\d{2}.\d{2}.\d{2}$/

Edit: Final form of model should be:

new TextboxQuestion({
        key: 'version',
        label: 'Release Number',
        type: 'text',
        required: true,
        order: 4,
        pattern: /^\d{2}.\d{2}.\d{2}.\d{2}$/ // needed format: ##.##.##.##
 })
Sign up to request clarification or add additional context in comments.

5 Comments

I did two more changes that I forgot to mention. 25.25.25.25 is not a valid number but it's of type text. Also I changed the pattern inside the service from '^\d{2}.\d{2}.\d{2}.\d{2}$' to /^\d{2}.\d{2}.\d{2}.\d{2}$/. Dunno why string does not work but regex does. Updated my answer.
the requirement is i dont want user to enter the text/characters in the input element and the reason i am accessing the pattern from other file is, pattern will be varied based on the user logged-in and account type he has access to.
Added more code to make it clear on how I made it work.
hey, could you please save the link?, i can't see your code
All changed code is in the answer but I also saved the link if you want to see a working example.stackblitz.com/edit/angular-dkrrhs-8cdzcz

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.