MVC
MVC

Reputation: 679

How to do server and client side validation which should only accept URL in textbox?

I want to do client and server side validation for Textbox which should only accept URL. I am not able find any link which does the same.

Can anyone please provide some ideas?

@Html.TextBoxFor(m => URl })

Upvotes: 1

Views: 530

Answers (3)

user3559349
user3559349

Reputation:

There is already a UrlAttribute in the System.ComponentModel.DataAnnotations that you can apply to your property to give both client and server side validation.

[Url] // Add optional (ErrorMessage = "...") as required
public string Url { get; set; }

Internally, it uses the following regex (from source code)

^(https?|ftp)://(((([a-z]|\d|-|.||~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'()*+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]).(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]).(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]).(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|.||~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))).)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))).?)(:\d*)?)(/((([a-z]|\d|-|.||~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'()*+,;=]|:|@)+(/(([a-z]|\d|-|.||~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'()*+,;=]|:|@)))?)?(\?((([a-z]|\d|-|.||~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'()*+,;=]|:|@)|[\uE000-\uF8FF]|/|\?)*)?(#((([a-z]|\d|-|.||~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'()*+,;=]|:|@)|/|\?)*)?$

Upvotes: 2

Hiren Patel
Hiren Patel

Reputation: 1157

You can do URL Validation using regex for validation.

^http(s)?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?$

OR

/^http(s)?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?$/

You can this regex in both Server-Side and Javascript.

check it on : JSFIDDLE

Upvotes: 1

Hooman Bahreini
Hooman Bahreini

Reputation: 15569

You can use a RegularExpression validation in your model:

[StringLength(200)]
[RegularExpression(@"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)", ErrorMessage = "Not a valid website URL")]
public string MyUrlField { get; set; }

I have found the above regex for matching a url from here. You could also check this website for other regex which would match a url.

Note that you need to include jquery-validation-unobtrusive, for the client side validation.

Upvotes: 1

Related Questions