让用户输入格式正确的 URL 的最佳方法?
我正在使用 MVVM 创建一个对话框,提示用户输入 KML 文件的 http:// URL。当 URL 格式正确时,需要启用“确定”按钮;当 URL 格式不正确时,需要禁用“确定”按钮。
现在,按钮绑定到 ICommand,CanExecute() 的逻辑如下所示:
return !string.IsNullOrEmpty(CustomUrl);
每次击键时都会引发该命令的 CanExecuteChanged 事件,到目前为止,它运行良好。
现在我想做一些实际验证。我知道做到这一点的唯一方法如下:
try
{
var uri = new Uri(CustomUrl);
}
catch (UriFormatException)
{
return false;
}
return true;
这可不是什么好事,特别是因为每次击键都会进行验证。我可以做到这一点,以便在用户单击“确定”按钮时验证 URI,但我不想这样做。除了捕获异常之外,是否有更好的方法来验证 URI?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的 - 您可以使用静态方法
Uri.IsWellFormedUriString< /code>
为此
Yes - you can use the static method
Uri.IsWellFormedUriString
for this我认为可能的解决方案有两个:
Uri.TryCreate
方法以避免异常(如果不需要创建Uri对象,可以使用Uri.IsWellFormedUriString
方法);我更喜欢使用第二个选项,创建正确的正则表达式可能很困难,并且可能会导致许多问题。
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 useUri.IsWellFormedUriString
method);I would prefer to use the second option, creating a correct RegEx could be difficult and could lead to many problems.
您可以将 ValidationRules 添加到控件,验证将“神奇地”完成。
You can add ValidationRules to the control and validation will be done "by magic".
您只需使用 Regex.IsMatch
而且,这是一个可靠的模式:
You can just use Regex.IsMatch
And, here's a reliable pattern:
由于您已经挂钩了击键事件,因此您可以对字符串使用正则表达式验证,然后由您决定是否将其标记为无效或根本不允许它。此帖子类似,并且具有有效 URI 的正则表达式。
Since you're already hooking into the keystroke event, you can use regular expression validation on the string, then it's up to you whether to flag it as invalid or not allow it at all. This post is similar and has the regular expression for a valid URI.