can some one tell me how can i validate a url like http://www.abc.com
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.
The ModelState has two purposes: to store and submit POSTed name-value pairs, and to store the validation errors associated with each value.
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.
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 ));
}
}
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With