can some one tell me how can i validate a url like http://www.abc.com
A:
Use a regular expression data annotation, and use a regex like:
http://www\.\w+\.(com|net|edu|org)
Depending on what you need to validate; are you requiring http: or are you requiring www.? So that could change the regular expression, if optional, to:
(http://)?(www\.)?\w+\.(com|net|edu|org)
Brian
2010-06-17 12:26:48
A:
If, by the title of your post, you want to use MVC DataAnnotations to validate a url string, you can write a custom validator:
public class UrlAttribute : ValidationAttribute
{
public UrlAttribute() { }
public override bool IsValid(object value)
{
//may want more here for https, etc
Regex regex = new Regex(@"(http://)?(www\.)?\w+\.(com|net|edu|org)");
if (value == null) return false;
if (!regex.IsMatch(value.ToString())) return false;
return true;
}
}
Phil Haack has a good tutorial that goes beyond this and also includes adding code to validate on the client side via jQuery: http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx
Michael Finger
2010-06-17 15:22:48