10

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?

3
  • assign a domain name to local host like mysampleapp.com. You can do it by mapping the localhost IP to this app name in hosts file. OR see here - codeproject.com/Articles/1463/… Commented Apr 13, 2015 at 6:42
  • The source is here: referencesource.microsoft.com/… Seems like you just need to match the Regex given - and it's a doozy Commented Apr 13, 2015 at 6:44
  • 2
    You have ErrorMessage = "please_enter_valid_ftp_url" and , ErrorMessage = null, i think the one with null need to be removed. Commented Apr 13, 2015 at 6:46

5 Answers 5

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

If I get you right you could use custom ValidationAttribute. Add this class in the Models namespace

public class UrlValidator : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            var x = value.ToString();
            if (Regex.IsMatch(x, @"^http:\/\/\w+(\.\w+)*(:[0-9]+)?\/?(\/[.\w]*)*$", RegexOptions.IgnoreCase))
            {
                return ValidationResult.Success;
            }
            else
            {
                return new ValidationResult(ErrorMessage);
            }
        }
        else
        {
            return new ValidationResult("Please enter some value");
        }
    }
}

and use it like

[UrlValidator(ErrorMessage = "please_enter_valid_ftp_url")] 
public string Url { get; set; }

Of course you can modify the regex expression to suit your requirements. The one i've used in this particular example is valid for addressess like

http://example
http://example.com
http://127.0.0.1

Comments

0

You could use 127.0.0.1:portNumber. Maybe this helps.

Comments

0

Regarding to URLAttribute code you have 3 options:

  1. Using IP address instead of localhost
  2. Using valid url and insert entry in your host file
  3. Create new URLAttribute extension and ignore the Localhost there

Comments

0

A bit late to the game, but I needed this combined with form validation on the cliend side. So I went this way:

public class ApiFormModel : PageModel
{
    [PageRemote(PageHandler = "CheckUri",
        HttpMethod = "post",
        AdditionalFields = "__RequestVerificationToken,AppId",
        ErrorMessage = "Url_Error")]
    [BindProperty]
    public string? AppRedirectUri { get; set; }


    public IActionResult OnPostCheckUri() =>
        new JsonResult(Uri.TryCreate(AppRedirectUri, UriKind.Absolute, out _));
}

And in the razor page:

<input type="text" asp-for="AppRedirectUri">

Together with some npm packages you get a nice looking form with client side validation of the uri

enter image description here

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.