Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can validate urls in C# for localhost

Tags:

c#

asp.net-mvc

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?

like image 258
user Avatar asked Apr 13 '15 06:04

user


People also ask

How do you check if a URL is valid or not in node?

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.

What is a valid URL format?

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 ).

How can check URL valid or not in android?

Use URLUtil to validate the URL as below. It will return True if URL is valid and false if URL is invalid.


1 Answers

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.

like image 55
Humaid Ashraf Avatar answered Sep 17 '22 13:09

Humaid Ashraf