I am using UrlAttribute in MVC
but its not accepting the localhost urls e.g http://localhost/GCWeb
[Url(ErrorMessage = "please_enter_valid_ftp_url", ErrorMessage = null)]
public string Url { get; set; }
This validates the urls but not for localhost urls.
How can I do this?
Other easy way is use Node. JS DNS module. The DNS module provides a way of performing name resolutions, and with it you can verify if the url is valid or not.
A typical URL could have the form http://www.example.com/index.html , which indicates a protocol ( http ), a hostname ( www.example.com ), and a file name ( index. html ).
Use URLUtil to validate the URL as below. It will return True if URL is valid and false if URL is invalid.
I also suggest to create a custom validator attribute class. But I'd like to use System.Uri class to validate instead of custom personal regex.
public class UriAttribute: ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
Uri uri;
bool valid = Uri.TryCreate(Convert.ToString(value), UriKind.Absolute, out uri);
if (!valid)
{
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
}
By using System.Uri class, we can leave out chances of error for own regex.
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