views:

373

answers:

1

Apologies for cross posting (I asked this on the Silverlight Forum but got no response)

I have an entity that I am trying to use validation on so I have decorated a property like so:

[Required]
[StringLength(10)]
public string Code
{
get
{
return this.code;
}

set
{
if (this.code != value)
{
this.code = value;
this.SendPropertyChanged("Code");
}
}
}

I have a list of these objects bound to a grid. If I put an empty entry in, it shows a validation error. If I put too long a code in, I get a validation error. Perfect! Except...

I want to be able to stop the user from saving the entity so I added the following to my entity:

public bool IsValid()
{
    try
    {
        this.Validate();
    }
    catch
    {
        return false;
    }
    return true;
}

public void Validate()
{
    var ctx = new ValidationContext(this, null, null);
    Validator.ValidateObject(this, ctx);
}

And when i go to save I call the IsValid method on each object and not save if it's false. This works fine for the required attribute (it wont save if Code is empty) but not for StringLength (I can save with any length code).

I have reproduced this in a simple project here:

http://walkersretreat.co.nz/files/Slvalidation.zip

Can anyone help?

Thanks!

Mark

A: 

Hello, you should write as:

[CustomValidation( typeof( MyExtraClassValidation ), "Validate" )]
public class MyExtraClass : Entity, IEditableObject, INotifyPropertyChanged
{
   /****/
}


public class MyExtraClassValidation 
{
    public MyExtraClassValidation ()
    {}

    public static ValidationResult Validate( MyExtraClass myExtraClass )
    {
        if ( /**class is not valid*/)
            return new ValidationResult( "Oops" );

        return ValidationResult.Success;
    }

}

Of course, your interfaces may be ablolutely anorther, but I reccomend you use it.

Also, you can call validateHandler from your control and check, for example, after every user key pressing.

Manushin Igor