简体   繁体   中英

How to write regex for domain validation that will trigger pattern error in Angular form

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM