CustomValidation属性似乎不工作 [英] CustomValidation attribute doesn't seem to work
问题描述
我有一个简单的测试页面中,我试图让一个自定义的验证规则,以便我的Silverlight 4应用程序。
我有一个文本框和一个按钮,我显示一个TextBlock验证结果。我的观点模型有一个名称属性,这势必TextBox的Text属性。我对Name属性两个验证属性, [必需]
和 [CustomValidation]
。
当我打的提交按钮,所需要的验证火灾正确的,但我的自定义验证程序的验证方法从来没有被击中里面的断点。我不明白这是为什么,因为我觉得我非常小心地遵循MS的例子:的 http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute(v = VS.95)的.aspx
下面是视图模型的代码:
使用系统;
使用System.Collections.Generic;使用System.ComponentModel.DataAnnotations
;
使用System.Linq的;
使用GalaSoft.MvvmLight.Command;
命名空间MyProject的
{
//自定义的验证类
公共类StartsCapitalValidator
{
公共静态的ValidationResult的IsValid(字符串值)
{
//此代码永远不会被击中
如果(value.Length大于0)
{
VAR有效=(值[0]的ToString()==值[0]的ToString()ToUpper的())。 (!有效)
如果
返回新的ValidationResult(名称必须以大写字母开头);
}
返回ValidationResult.Success;
}
}
//我的视图模型
公共类ValidationTestViewModel:ViewModelBase
{
//属性进行验证
字符串_name;
[必填]
[CustomValidation(typeof运算(StartsCapitalValidator)的IsValid)]
公共字符串名称
{
{返回_name; }
集合{的SetProperty(REF _name,价值,()=>名称); }
}
串_result;
公共字符串结果
{
{返回_result; }
私人集合{的SetProperty(REF _result,价值,()=>结果); }
}
公共RelayCommand SubmitCommand {搞定;私人集; }
公共ValidationTestViewModel()
{
SubmitCommand =新RelayCommand(提交);
}
无效提交()
{
//执行验证,当用户点击提交按钮
VAR误差=新的List<为ValidationResult>( );
如果(!Validator.TryValidateObject(这一点,新ValidationContext(本,NULL,NULL),错误))
{
//我们永远只能到这里从所需验证,永远不会从的CustomValidator
结果=的String.Format({0}个错误:\\\
{1},
errors.Count,
的string.join(\\\
errors.Select(E => e.ErrorMessage)));
}
,否则
{
结果=有效;
}
}
}
}
下面认为:
<导航:第x页:类=Data.Byldr.Application.Views.ValidationTest
的xmlns =http://schemas.microsoft.com/winfx/2006/xaml/presentation
的xmlns:X =http://schemas.microsoft.com/winfx/2006/xaml
的xmlns:D =http://schemas.microsoft.com/expression/blend/2008
的xmlns:MC =http://schemas.openxmlformats.org/markup-compatibility/2006
的xmlns:导航=CLR的命名空间:System.Windows.Controls;装配= System.Windows.Controls.Navigation>
<电网WIDTH =400>
<&StackPanel的GT;
<文本框的文本={绑定名称,模式=双向}/>
<按钮命令={结合SubmitCommand}CONTENT =提交/>
< TextBlock的文本={结合}的结果/>
< / StackPanel的>
< /网格和GT;
< /导航:第>
至于那超负荷的MSDN页面上注明 Validator.TryValidateObject
( HTTP ://msdn.microsoft.com/en-us/library/dd411803(v = VS.95)的.aspx 的),只有对象级验证用这种方法检查,并且RequiredAttribute标签上的属性。 p>
要查看属性级别的验证,使用重载,还需要一个布尔(的 http://msdn.microsoft.com/en-us/library/dd411772(v = VS.95)的.aspx )
所以应该是传递真作为一个额外的参数 TryValidateObject
那么简单
I have a simple test page in my Silverlight 4 application in which I'm trying to get a custom validation rule to fire.
I have a TextBox and a Button, and I am showing the validation results in a TextBlock. My view model has a Name property, which is bound the the Text property of the TextBox. I have two validation attributes on the Name property, [Required]
and [CustomValidation]
.
When I hit the Submit button, the Required validator fires correctly, but the breakpoint inside the validation method of my custom validator never gets hit. I can't see why this is, as I think I have followed MS's example very carefully: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute(v=vs.95).aspx
Here is the code for the view model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using GalaSoft.MvvmLight.Command;
namespace MyProject
{
// custom validation class
public class StartsCapitalValidator
{
public static ValidationResult IsValid(string value)
{
// this code never gets hit
if (value.Length > 0)
{
var valid = (value[0].ToString() == value[0].ToString().ToUpper());
if (!valid)
return new ValidationResult("Name must start with capital letter");
}
return ValidationResult.Success;
}
}
// my view model
public class ValidationTestViewModel : ViewModelBase
{
// the property to be validated
string _name;
[Required]
[CustomValidation(typeof(StartsCapitalValidator), "IsValid")]
public string Name
{
get { return _name; }
set { SetProperty(ref _name, value, () => Name); }
}
string _result;
public string Result
{
get { return _result; }
private set { SetProperty(ref _result, value, () => Result); }
}
public RelayCommand SubmitCommand { get; private set; }
public ValidationTestViewModel()
{
SubmitCommand = new RelayCommand(Submit);
}
void Submit()
{
// perform validation when the user clicks the Submit button
var errors = new List<ValidationResult>();
if (!Validator.TryValidateObject(this, new ValidationContext(this, null, null), errors))
{
// we only ever get here from the Required validation, never from the CustomValidator
Result = String.Format("{0} error(s):\n{1}",
errors.Count,
String.Join("\n", errors.Select(e => e.ErrorMessage)));
}
else
{
Result = "Valid";
}
}
}
}
Here is the view:
<navigation:Page x:Class="Data.Byldr.Application.Views.ValidationTest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation">
<Grid Width="400">
<StackPanel>
<TextBox Text="{Binding Name, Mode=TwoWay}" />
<Button Command="{Binding SubmitCommand}" Content="Submit" />
<TextBlock Text="{Binding Result}" />
</StackPanel>
</Grid>
</navigation:Page>
As stated on the MSDN page for that overload of Validator.TryValidateObject
( http://msdn.microsoft.com/en-us/library/dd411803(v=VS.95).aspx ), only the object-level validations are checked with this method, and RequiredAttribute on properties.
To check property-level validations, use the overload that also takes a bool ( http://msdn.microsoft.com/en-us/library/dd411772(v=VS.95).aspx )
So it should be as simple as passing "true" as an extra parameter to TryValidateObject
这篇关于CustomValidation属性似乎不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!