2

I'm trying to validate a filename string in Angular2 form. The filename string cannot be all dots and cannot contain this characters \ / ? * " : < > |

I solve the second requirement and my regex looks like this:

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

but I'm not sure how to solve the dots requirement.

1 Answer 1

2

You may use a (?!\.+$) negative lookahead at the start that will prevent matching a string that consists only of 1 or more dots:

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

or even remove ^ and last $ since Angular will add them automatically:

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

Note that *?"<>|/ chars do not need to be escaped inside the character class. all of them are treated as literal symbols there.

Sign up to request clarification or add additional context in comments.

5 Comments

is there an elegant way to return an error if there are spaces only after the dots?
@KaloyanStamatov If you mean trailing whitespace, use Validators.pattern('(?!\\.+\\s*$)[^\\\\:*?"<>|/]+'), if leading and trailing - Validators.pattern('(?!\\s*\\.+\\s*$)[^\\\\:*?"<>|/]+')
Аmazing, again thanks a lot, you save me a lot of time!
I'v noticed that if I have string like '. . .' or '. . . ', the validation fails. Could you help me with that case as well in order to have fully functional validation? My pattern is to avoid name with only dots and spaces.
@KaloyanStamatov Replace the lookahead at the start with (?!\\s*(?:\\.\\s*)+$). You may also use Validators.pattern(/^(?!\s*(?:\.\s*)+$)[^\\:*?"<>|\/]+$/)

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.