简体   繁体   English

CustomValidation属性似乎不起作用

[英]CustomValidation attribute doesn't seem to work

I have a simple test page in my Silverlight 4 application in which I'm trying to get a custom validation rule to fire. 我在Silverlight 4应用程序中有一个简单的测试页面,我正在尝试获取自定义验证规则。

I have a TextBox and a Button, and I am showing the validation results in a TextBlock. 我有一个TextBox和一个Button,我在TextBlock中显示验证结果。 My view model has a Name property, which is bound the the Text property of the TextBox. 我的视图模型有一个Name属性,它绑定了TextBox的Text属性。 I have two validation attributes on the Name property, [Required] and [CustomValidation] . 我在Name属性上有两个验证属性, [Required][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 我不明白为什么会这样,因为我认为我非常仔细地遵循了MS的例子: 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. 如MSDN页面上针对Validator.TryValidateObjecthttp://msdn.microsoft.com/en-us/library/dd411803 ( v=VS.95 ) .aspx )的重载所述,仅检查对象级验证使用此方法,以及属性上的RequiredAttribute。

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 ) 要检查属性级验证,请使用也需要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 因此,它应该像将“true”作为额外参数传递给TryValidateObject一样简单

Why don't you create your own Validation attribute like this.. 为什么不像这样创建自己的Validation属性..

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

public class StartsCapital : ValidationAttribute 
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var text = value as string;

            if(text == null)
                return ValidationResult.Success;

            if (text.Length > 0)
            {
                var valid = (text[0].ToString() == text[0].ToString().ToUpper());
                if (!valid)
                    return new ValidationResult("Name must start with capital letter");
            }
            return ValidationResult.Success;
        }
}

And then use it like 然后像使用它一样

 // my view model
public class ValidationTestViewModel : ViewModelBase
{
    // the property to be validated
    string _name;
    [Required]
    [StartsCapital]
    public string Name
    {
        get { return _name; }
        set { SetProperty(ref _name, value, () => Name); }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM