1

How do i catch the validation from the DataAnnotations ? i research here but i didn't understand how it works

so i hoppe some of you can enlighten my

here my current test code:

Model

public class Person // Represents person data.
{
    /// <summary>
    /// Gets or sets the person's first name.
    /// </summary>
    /// <remarks>
    /// Empty string or null are not allowed.
    /// Allow minimum of 2 and up to 40 uppercase and lowercase.
    /// </remarks>
    [Required]
    [RegularExpression(@"^[a-zA-Z''-'\s]{2,40}$")]        
    public string FirstName{ get; set;}

    /// <summary>
    /// Gets or sets the person's last name.
    /// </summary>
    /// <remarks>
    /// Empty string or null are not allowed.
    /// </remarks>
    [Required]
    public string LastName { get; set;}

    public int Age{ get; set;}
}

View

<Window x:Class="DataAnnotationstest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:DataAnnotationstest"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:Person FirstName="Tomer" LastName="Shamam" />
    </Window.DataContext>
    <Grid>
        <StackPanel Margin="4,4,51,4">
            <TextBox Text="{Binding FirstName, ValidatesOnDataErrors=True}" />
            <TextBox Text="{Binding LastName, ValidatesOnDataErrors=True}" />
            <TextBox Text="{Binding Age, ValidatesOnDataErrors=True}" />
        </StackPanel>
    </Grid>
</Window>

do i need to implement something else to Person? i found here the following code but like i said before i didn't understand how it's worke -.-

public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
    var attrType = typeof(T);
    var property = instance.GetType().GetProperty(propertyName);
    return (T)property .GetCustomAttributes(attrType, false).First();
}
Community
  • 1
  • 1
Karl_Schuhmann
  • 1,272
  • 5
  • 17
  • 37
  • What do you want exactly? Do you want to know if your Notifying has ValidationErrors or do you want to Validate an instance to check if it has validationerrors – Jehof Oct 30 '12 at 11:53
  • if the user doesn't insert an Id an the Id is null the DataAnnotations will return an Error right? and now i wane catch this Error in my ZusatzstoffVM but i doesnt know how my Notifying will than set his HasError to true thats my plan ^^ – Karl_Schuhmann Oct 30 '12 at 11:58
  • i replaced my code sample with a shorter one – Karl_Schuhmann Oct 30 '12 at 15:56
  • 2
    I think you need to implement [IDataErrorInfo](http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo(v=vs.95).aspx) to make use of WPF's binding validation system, and you'll need to check for DataAnnotation errors in the `this[string propertyName]` method – Rachel Oct 30 '12 at 16:06

1 Answers1

7

the solution

public class Person : IDataErrorInfo // Represents person data.
{
    /// <summary>
    /// Gets or sets the person's first name.
    /// </summary>
    /// <remarks>
    /// Empty string or null are not allowed.
    /// Allow minimum of 2 and up to 40 uppercase and lowercase.
    /// </remarks>
    [Required]
    [RegularExpression(@"^[a-zA-Z''-'\s]{2,40}$")]        
    public string FirstName{ get; set;}

    /// <summary>
    /// Gets or sets the person's last name.
    /// </summary>
    /// <remarks>
    /// Empty string or null are not allowed.
    /// </remarks>
    [Required]
    public string LastName { get; set;}

    public int Age{ get; set;}

    public string Error // Part of the IDataErrorInfo Interface
    {
        get { throw new NotImplementedException(); }
    }

 string IDataErrorInfo.this[string propertyName] // Part of the IDataErrorInfo Interface
    {
        get { return OnValidate(propertyName); }
    }

    /// <summary>
    /// Validates current instance properties using Data Annotations.
    /// </summary>
    /// <param name="propertyName"></param>
    /// <returns></returns>
    protected virtual string OnValidate(string propertyName)
    {
        if (string.IsNullOrEmpty(propertyName))
            throw new ArgumentException("Invalid property name", propertyName);

        string error = string.Empty;
        var value = this.GetType().GetProperty(propertyName).GetValue(this, null);
        var results = new List<ValidationResult>(1);

        var context = new ValidationContext(this, null, null) { MemberName = propertyName };

        var result = Validator.TryValidateProperty(value, context, results);

        if (!result)
        {
            var validationResult = results.First();
            error = validationResult.ErrorMessage;
        }

        return error;
    }
}

thanks to Rachel for here hint and to this link which was very enlightened

Karl_Schuhmann
  • 1,272
  • 5
  • 17
  • 37