Home > Enterprise >  Angular FormControl validation with regex: textarea lines should not start with special characters
Angular FormControl validation with regex: textarea lines should not start with special characters

Time:01-07

I have a textarea with a simple FormControl, which I'd like to validate via the Validators.pattern() method. None of the new lines should be started with a ? or *. That's all the requirements.

I've tried the following:

control = new FormControl('', Validators.pattern(/^(\?|\*)$/));

With this, I can validate the first line (works well if the line starts with a special character), but as soon as I hit enter my FormControl will be invalid.

How should I tweak the regex to meet the requirements?

CodePudding user response:

Since you are dealing with a textarea you need to emulate the \A meta escape which is "start of string not line"

/(?<!\s)^(?![\s\S]*^[?*])/gm
  • (?<!\s)^ - detect the start of the string
  • (?![\s\S]*^[?*]) - Ahead of me cannot be any line which starts with a question mark nor asterisk
    • [\s\S]* - capture everything, even new lines
    • ^[?*] - detect a line which starts with a question mark or asterisk

https://regex101.com/r/NacQst/1

CodePudding user response:

You can use

// With a string literal where anchors are added automatically by Angular
control = new FormControl('', Validators.pattern('(?![?*]).*(?:[\r\n] (?![?*]).*)*'));
// Or, with a regex literal
control = new FormControl('', Validators.pattern(/^(?![?*]).*(?:[\r\n] (?![?*]).*)*$/));

See the regex demo. Details:

  • ^ - string start anchor
  • (?![?*]) - no ? and * are allowed immediately to the right of the current location
  • .* - zero or more chars other than line break chars as many as possible
  • (?: - start of a non-capturing group:
    • [\r\n] - one or more CR / LF chars (carriage return or line feed chars)
    • (?![?*]).* - a line that does not start with ? nor *
  • )* - end of group, zero or more occurrences
  • $ - end of the string.
  •  Tags:  
  • Related