1

I need to my input field to obey these 2 expressions:

1 - /^[^.\?\\\/\:\*\<\>\|\"\']*[^\?\\\/\:\*\<\>\|\"\']*[^.\?\\\/\:\*\<\>\|\"\']+$/

2 - /^[^\s].*/

  1. Means that the input cannot have these special characters and can't end with .
  2. Means that the input cannot start with a blank space

Is there a way that can use these two expressions like:

Validators.pattern(/^[^.\?\\\/\:\*\<\>\|\"\']*[^\?\\\/\:\*\<\>\|\"\']*[^.\?\\\/\:\*\<\>\|\"\']+$/ && /^[^\s].*/)])]
2
  • You need to use negative look-ahead, like this: ^(?!.*\*)(?!.*\.$) and add your stuff to it. ^(?!.*\*) means doesn't contain a * and (?!.*\.$) means doesn't end with . You can add your other rules the same way. It's a better way to validate lines even if the expressions can be combined somehow. Commented Mar 3, 2021 at 13:35
  • You can actually easily merge these two into a single regex. Commented Mar 3, 2021 at 18:08

2 Answers 2

1

You can compose multiple validators:

Validators.compose(
    Validators.pattern('<pattern A>'),
    Validators.pattern('<pattern B>'),
)
Sign up to request clarification or add additional context in comments.

Comments

0

The /^[^.\?\\\/\:\*\<\>\|\"\']*[^\?\\\/\:\*\<\>\|\"\']*[^.\?\\\/\:\*\<\>\|\"\']+$/ can be written as /^[^.?\\\/:*<>|"']*[^?\\\/:*<>|"']*[^.?\\\/:*<>|"']+$/ if all unnecesary backslashes are removed.

Then, the /^[^\s].*/ regex just requires a string to start with a non-whitespace char.

So, all you need is to add a (?=\S) lookahead at the start:

Validators.pattern(/^(?=\S)[^.?\\\/:*<>|"']*[^?\\\/:*<>|"']*[^.?\\\/:*<>|"']+$/)
//                   ^^^^^^

See the regex demo.

It also seems too redundant to have two optional subpatterns at the start, see [^.?\\\/:*<>|"']*[^?\\\/:*<>|"']*. It makes sense to further shrink it to

Validators.pattern(/^(?=\S)[^?\\\/:*<>|"']*[^.?\\\/:*<>|"']+$/)

It matches

  • ^ - start of string
  • (?=\S) - a lookahead requiring the first char to be a char other than whitespace
  • [^?\\\/:*<>|"']* - zero or more chars other than ?, \, /, :, *, <, >, |, " and '
  • [^.?\\\/:*<>|"']+ - one or more chars other than ., ?, \, /, :, *, <, >, |, " and '
  • $ - end of string.

Comments

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.