使用数据注释属性验证方法参数

发布于 2024-09-03 20:14:12 字数 797 浏览 3 评论 0原文

与 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 类方法中实现此功能,如何让框架调用验证或如何强制调用所有参数的验证(使用验证器或其他方式?)。

The "Silverlight Business Application" template bundled with VS2010 / Silverlight 4 uses DataAnnotations on method arguments in its domain service class, which are invoked automagically:

        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 */ }

If I need to implement this in my POCO class methods, how do I get the framework to invoke the validations OR how do I invoke the validation on all the arguments imperatively (using Validator or otherwise?).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

愿与i 2024-09-10 20:14:12

我们是这样处理的:

我们有一个 ValidationProperty 类,它接受一个正则表达式,该表达式将用于验证值(您可以使用您想要的任何内容)。

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
}

以下是我们创建验证属性的方法。请注意公共成员是一个字符串,但我私下使用的是“ValidationProperty”。

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

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

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

通过这种方法,您可能会有一个用于创建新“用户”的表单,并且每个字段每次设置时都会进行验证(我希望这是有意义的)。

这是我们用来在业务层进行验证的方法。我不确定这是否正是您正在寻找的,但我希望它有所帮助。

We have approached it like this:

We have a ValidationProperty class that takes in a RegularExpression that will be used to validate the value (you could use whatever you wanted).

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
}

Here's how we would create a Validation property. Notice how the public member is a string, but privately I am using a 'ValidationProperty.'

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

Now, whenever the value is set, the business layer will validate that it's a valid value. If it's not, it will simply throw a new ValidationException (in the ValidationProperty class). In your xaml, you will need to set NotifyOnValidationError & ValidatesOnExceptions to true.

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

With this approach, you would probably have a form for creating a new 'User' and each field would valitate each time they set it (I hope that makes sense).

This is the approach that we used to get the validation to be on the business layer. I'm not sure if this is exactly what you're looking for, but I hope it helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文