1

I am validating a domain field in the form. I am using Validators.pattern(this.domainPattern) for doing that. I am using below pattern:

public domainPattern: string = "^(?:[a-z0-9][a-z0-9-]{0,61}[a-z0-9]\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$";

It works fine for many cases. But when there is a white space in domain it is not triggering pattern error. What I am missing?

Quick help will be highly appreciated.

Thanks.

6
  • Add sample strings that should pass validation, show us what should pass and does not pass, explain your logic for regex. Commented Mar 26, 2019 at 5:06
  • google.com abc.co.in should pass. But goo gle.com should not pass Commented Mar 26, 2019 at 5:13
  • Here you can check, how it is behaving currently Commented Mar 26, 2019 at 5:25
  • This is impossible to answer without knowing what you really want. I can type this-s.asjfjff.validdddd-cddddd for example and tihs is valid. Is this supposed to be valid? Commented Mar 26, 2019 at 8:11
  • By the way, your pattern doesn't accept whitespace so if you are matching whitespace there is a problem elsewhere, not in the regex pattern. Commented Mar 26, 2019 at 8:12

1 Answer 1

4

Try this pattern:

(?(?<= )(?=[^ ])|^)(?:[a-z0-9][a-z0-9-]{0,61}[a-z0-9]\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]

I just added (?(?<= )(?=[^ ])|^), conditional which checks:

first it checks condition (?<= ) if what is preceeding is space, if it is, then check if what's after is not a space with (?=[^ ]), if the condition fails, then check if we are at the beginning of a string with ^.

Demo

UPDATE

OP said:

I want user to enter just one valid domain name. If user enters "google.com google.com" it should be treated as invalid

Then you could use this pattern

^(?!.* .*)(?:[a-z0-9][a-z0-9-]{0,61}[a-z0-9]\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$

Just added (?!.* .*) which checks if there's sapce in following line, if it is, then it won't match anything, as space indicated multiple domain names.

Another demo

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

2 Comments

Thanks for that @Michal. But in my case, I want user to enter just one valid domain name. If user enters "google.com google.com" it should be treated as invalid.
Thanks @MichalTurczyn. It works as expected. I was struggling for this since yesterday.

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.