WinRT XAML Validation library: Async Validation Attributes

Last posts have shown how basic validation attributes and property-group based validation attributes can be used to define custom validation logic, that goes beyond the default capabilities of Data Annotations. There’s another validation attribute base class in the WinRT XAML Validation library and that’s the AsyncValidationAttribute and its sister, the AsyncGroupValidationAttribute.

Both attributes define the abstract method IsValidAsync(), which you can use in your derived validation attribute classes to perform asynchronous operations during validation. The following code gives an example for the AsyncValidationAttribute class:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ValidateActualCurrentBidAttribute : AsyncValidationAttribute
{
    protected override async Task<ValidationResult> IsValidAsync(object value, ValidationContext validationContext)
    {
        var newBid = (double)value;
        var auctionBid = (AuctionBid)validationContext.ObjectInstance;
            
        var service = new AuctionService();
        var currentBid = await service.GetCurrentBidAsync(auctionBid);

        return (newBid > auctionBid.CurrentBid && newBid <= currentBid)
            ? new ValidationResult("Your bid has been surpassed.")
            : ValidationResult.Success;
    }
}

This sample async validation attribute calls the async service method AuctionService.GetCurrentBidAsync() to retrieve actual data from a server. It gets await’ed and returns the validation result after the async operations has returned. Thus you’re able to define custom validation logic in our asynchronous app world.

AsyncGroupValidationAttribute is a specialization of AsyncValidationAttribute, its usage doesn’t differ, so I will not show it here. The usage of an async validation attribute equals the usage of any other attribute on your entity and you’re able to use the functionality of the ExtendedValidationAttribute.

public class AuctionBid : ValidationBindableBase
{
    [ValidateActualCurrentBid(UseInImplicitValidation = false)]
    public double NewBid { ... }
}

Ein Gedanke zu „WinRT XAML Validation library: Async Validation Attributes“

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.