Sana Assistant (online)
Table of Contents

BasketValidationResult Class

The BasketValidationResult class represents the outcome of a basket validation operation. It provides a standardized way to indicate whether the validation was successful and, in case of failure, includes a message explaining why the validation failed.

BasketValidationResult class diagram

Properties

IsValid

public bool IsValid { get; }

A boolean value indicating whether the basket passed validation. This property is read-only and is set through the factory methods.

Message

public string? Message { get; }

A string containing the validation message. This property is typically used to provide a user-friendly explanation when validation fails. It is nullable and is null for successful validations. This property is read-only and is set through the factory method.

Methods

Succeeded

public static BasketValidationResult Succeeded()

Creates a successful basket validation result. Use this method when the basket passes all validation checks.

Returns

A BasketValidationResult instance with IsValid set to true and no message.

Failed

public static BasketValidationResult Failed(string message)

Creates a failed basket validation result with a specified error message. Use this method when the basket fails validation checks.

Note

Use Api.GetSanaText to get the localized text for the message.

Parameters

  • message: A string explaining why the validation failed. This message should be user-friendly as it may be displayed to the end user.

Returns

A BasketValidationResult instance with IsValid set to false and the specified error message.

Example Usage

Here's an example of using BasketValidationResult in a validation rule:

public class MaxItemQuantityValidator : BasketValidationExtension
{
    public override ApplicableCheckoutProcesses AppliesTo =>
        ApplicableCheckoutProcesses.Order;

    public override Task<BasketValidationResult> ValidateAsync(BasketValidationContext context)
    {
        if (context.Account.Type == AccountType.Customer)
            return Task.FromResult(BasketValidationResult.Failed("Customer accounts cannot place orders."));

        return Task.FromResult(BasketValidationResult.Succeeded());
    }
}