Best way to get a user to input a correctly
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?
是的 - 你可以使用静态方法Uri.IsWellFormedUriString
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.
您可以将验证规则添加到控件,验证将“通过魔术”完成。
链接地址: http://www.djcxy.com/p/70230.html上一篇: 删除javascript和url中的域和http之后的所有内容
下一篇: 让用户正确输入的最佳方式