使用Data Annotation属性验证方法参数

时间:2010-06-03 09:14:14

标签: silverlight silverlight-4.0 data-annotations wcf-ria-services

与VS2010 / Silverlight 4捆绑在一起的“Silverlight业务应用程序”模板在其域服务类中的方法参数上使用DataAnnotations,这些参数可以自动调用:

        public CreateUserStatus CreateUser(RegistrationData user,
        [Required(ErrorMessageResourceName = "ValidationErrorRequiredField", ErrorMessageResourceType = typeof(ValidationErrorResources))]
        [RegularExpression("^.*[^a-zA-Z0-9].*$", ErrorMessageResourceName = "ValidationErrorBadPasswordStrength", ErrorMessageResourceType = typeof(ValidationErrorResources))]
        [StringLength(50, MinimumLength = 7, ErrorMessageResourceName = "ValidationErrorBadPasswordLength", ErrorMessageResourceType = typeof(ValidationErrorResources))]
        string password)
    { /* do something */ }

如果我需要在我的POCO类方法中实现它,我如何让框架调用验证或如何在命令性地调用所有参数的验证(使用Validator或其他?)。

1 个答案:

答案 0 :(得分:1)

我们这样接近它:

我们有一个ValidationProperty类,它接受一个RegularExpression,用于验证值(你可以使用你想要的任何东西)。

ValidationProperty.cs

public class ValidationProperty
{
    #region Constructors

    /// <summary>
    /// Constructor for property with validation
    /// </summary>
    /// <param name="regularExpression"></param>
    /// <param name="errorMessage"></param>
    public ValidationProperty(string regularExpression, string errorMessage)
    {
        RegularExpression = regularExpression;
        ErrorMessage = errorMessage;
        IsValid = true;
    }

    #endregion

    #region Properties

    /// <summary>
    /// Will be true if this property is currently valid
    /// </summary>
    public bool IsValid { get; private set; }

    /// <summary>
    /// The value of the Property.
    /// </summary>
    public object Value 
    {
        get { return val; }
        set 
        {
            if (this.Validate(value))//if valid, set it
            {
                val = value;
            }
            else//not valid, throw exception
            {
                throw new ValidationException(ErrorMessage);
            }
        }
    }
    private object val;

    /// <summary>
    /// Holds the regular expression that will accept a vaild value
    /// </summary>
    public string RegularExpression { get; private set; }

    /// <summary>
    /// The error message that will be thrown if invalid
    /// </summary>
    public string ErrorMessage { get; private set; }

    #endregion

    #region Private Methods

    private bool Validate(object myValue)
    {
        if (myValue != null)//Value has been set, validate it
        {
            this.IsValid = Regex.Match(myValue.ToString(), this.RegularExpression).Success;
        }
        else//still valid if it has not been set.  Invalidation of items not set needs to be handled in the layer above this one.
        {
            this.IsValid = true;
        }

        return this.IsValid;
    }

    #endregion
}

以下是我们如何创建Validation属性。注意公共成员是一个字符串,但私下我使用'ValidationProperty。'

public string TaskNumber
    {
        get { return taskNumber.Value.ToString(); }
        set 
        {
            taskNumber.Value = value;
            OnPropertyChanged("TaskNumber");
        }
    }
    private ValidationProperty taskNumber;

现在,无论何时设置该值,业务层都将验证它是否为有效值。如果不是,它只会抛出一个新的ValidationException(在ValidationProperty类中)。在你的xaml中,你需要设置NotifyOnValidationError&amp; ValidatesOnExceptions为true。

<TextBox Text="{Binding TaskNumber, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}"/>

通过这种方法,您可能会有一个表单来创建一个新的“用户”,并且每个字段在每次设置时都会有效(我希望这是有道理的)。

这是我们用于将验证放在业务层上的方法。我不确定这是不是你正在寻找的,但我希望它有所帮助。

相关问题