Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc dataannotation validating url

Tags:

asp.net-mvc

can some one tell me how can i validate a url like http://www.abc.com

like image 803
maztt Avatar asked Jun 17 '10 12:06

maztt


People also ask

Can we do validation in MVC using data annotations?

In ASP.NET MVC, Data Annotation is used for data validation for developing web-based applications. We can quickly apply validation with the help of data annotation attribute classes over model classes.

What is the use of ModelState in MVC?

The ModelState has two purposes: to store and submit POSTed name-value pairs, and to store the validation errors associated with each value.

How does ValidationMessageFor work in MVC?

ASP.NET MVC: ValidationMessageFor The Html. ValidationMessageFor() is a strongly typed extension method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object. Visit MSDN to know all the overloads of ValidationMessageFor() method.


2 Answers

Let the System.Uri do the heavy lifting for you, instead of a RegEx:

public class UrlAttribute : ValidationAttribute
{
    public UrlAttribute()
    {
    }

    public override bool IsValid(object value)
    {
        var text = value as string;
        Uri uri;

        return (!string.IsNullOrWhiteSpace(text) && Uri.TryCreate(text, UriKind.Absolute, out uri ));
    }
}
like image 58
Dan Marshall Avatar answered Oct 05 '22 17:10

Dan Marshall


Now (at least form ASP.NET MVC 5) you can use UrlAttribute and that includes server and client validation:

[Url]
public string WebSiteUrl { get; set; }
like image 29
Sebastián Rojas Avatar answered Oct 05 '22 17:10

Sebastián Rojas