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?
Yes - you can use the static method Uri.IsWellFormedUriString
for this
return Uri.IsWellFormedUriString (CustomUrl, UriKind.Absolute);
Possible solutions are two in my opinion:
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.
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