Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get a user to input a correctly-formatted URL?

I am creating a dialog using MVVM which prompts the user to type in an http:// URL to a KML file. The "OK" button needs to be enabled when the URL is in the correct format, and it needs to be disabled when the URL is in an incorrect format.

Right now the button is bound to an ICommand, and the logic for CanExecute() looks like this:

return !string.IsNullOrEmpty(CustomUrl);

The command's CanExecuteChanged event is raised on every keystroke, and so far it's working well.

Now I want to do a little bit of actual validation. The only way I know to do that is as follows:

try
{
    var uri = new Uri(CustomUrl);
}
catch (UriFormatException)
{
    return false;
}

return true;

That's no bueno, especially since the validation is happening on each keystroke. I could make it so that the URI is validated when the user hits the OK button, but I'd rather not. Is there a better way to validate the URI other than catching exceptions?

like image 543
Phil Avatar asked Oct 24 '11 19:10

Phil


2 Answers

Yes - you can use the static method Uri.IsWellFormedUriString for this

return Uri.IsWellFormedUriString (CustomUrl, UriKind.Absolute);
like image 178
Yahia Avatar answered Oct 20 '22 13:10

Yahia


Possible solutions are two in my opinion:

  • Create a regular expression that checks URL correctness;
  • Use Uri.TryCreate method in order to avoid exceptions (if you don't need to create an Uri object you can use Uri.IsWellFormedUriString method);

I would prefer to use the second option, creating a correct RegEx could be difficult and could lead to many problems.

like image 28
as-cii Avatar answered Oct 20 '22 14:10

as-cii