Click here to Skip to main content
16,017,279 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello, I'm trying to create a regex expression which creates validation for a target Url. Below are the rules I would like to include:

- must begin with http:// or https://
- path name must be between 1-63 characters
- no upper case characters allowed
- no spaces
- can only contain the following symbols "-", ".", "_", "~"

e.g.
https://www.sdsdsd-sdddf-manage.co.uk/news-and-events/news

Thanks!

What I have tried:

This is what I have so far:

^http://|https://[a-z0-9._~-]{1,63}[.][a-z{2,6}]$
Posted
Updated 12-Sep-22 5:19am
v2

1 solution

That isn't even close.
To select "http: or https:" you would need teh Regex "OR" operator '|'
RegEx
^((http:)|(https:)).*$
Matches any string that starts with "http:" or "https:"

But even with that, your rules are somewhat arbitrary: a valid URL can be much longer than 63 characters, and can include a much wider range of characters. ANd they don't have start with "http" at all - the browser will happily infer that.

Personally, I like regexes - but they can quickly become unwieldy and complicated, which makes them prone to error and hard to fix. I'd probably do the validation in C# in a couple of goes:
1) Does it start with "http:" or "https:"
2) Is it the right length?
...
That way, you get much more readable code that is a lot easier to modify when one of your rules is found to be wrong ... which they almost certainly will be!
 
Share this answer
 
Comments
Dave Kreskowiak 12-Sep-22 7:41am    
This question carriers the distinct odor of homework.
OriginalGriff 12-Sep-22 8:21am    
There is a strong whiff there, isn't there? :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900