Regex for Url Check

2.7k Views Asked by At

In my "ServiceEditModel" class i have a property Url with typeof Uri. For validation I search a Regex that check if the Url, which is filled up on my "Edit" page, is valid.
The Regex should check

  1. Is there a http:// or https://
  2. That the body only contains alphabetic characters and numbers
  3. And the ending is like for example .com, .net, .ch
  4. It should be possible, that there is another parameter behind the ending like for example https://stackoverflow.com/questions

My Code where the Regex comes in look like this:

[Required(ErrorMessageResourceType = typeof(Resources.ApplicationTemplate), ErrorMessageResourceName = "UrlRequired")]
[RegularExpression("REGEX COMES HERE", ErrorMessageResourceType = typeof(Resources.ApplicationTemplate), ErrorMessageResourceName = "InvalidUrl")]
public Uri Url { get; set; }

I already looked for Regex but can't find the right one because this is actually my first experiance with Regex.

Thanks for Help!

EDIT

I updated my regex so that it also allows url's with a "-" character such as http://www.comsoft-direct.ch/

Updated regex: ^(http|https):\/\/([\w\d + (\-)+?]+\.)+[\w]+(\/.*)?$

1

There are 1 best solutions below

12
On BEST ANSWER

This Regex should check simple scenarios according to your constraints. You can easily play with it and improve it (which I strongly recommend, firstly because it's very simple at this state and secondly because you are a Regex beginner :)).

^(http|https):\/\/[\w\d]+\.[\w]+(\/[\w\d]+)$

Check it on Regex 101

Basic explanation:

(http|https):\/\/

Should start with http or https, followed by ://

[\w\d]+

Followed by N letters and/or digits

\.[\w]+

Followed by a dot and a set of letters. e.g.: .com, .net and such (note that you must change to \.[\d\w]+ to allow digits also)

(\/[\w\d]+)

Followed, optionally, by a / and a set of letters and/or digits (e.g.: /questions)

NOTE: If you want a full-generic url validator, you must then google for that.