| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="ValidationNotificationExtensions.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System.Collections.Generic; |
| | | 8 | | using MyNet.Observable; |
| | | 9 | | using MyNet.Observable.Behaviors; |
| | | 10 | | |
| | | 11 | | #pragma warning disable IDE0130 |
| | | 12 | | namespace MyNet.UI.Notifications; |
| | | 13 | | #pragma warning restore IDE0130 |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Bridges <see cref="IValidationBehavior"/> with <see cref="INotificationPublisher"/>. |
| | | 17 | | /// </summary> |
| | | 18 | | public static class ValidationNotificationExtensions |
| | | 19 | | { |
| | | 20 | | extension(ObservableObject owner) |
| | | 21 | | { |
| | | 22 | | /// <summary> |
| | | 23 | | /// Validates the object and publishes validation errors when validation fails. |
| | | 24 | | /// </summary> |
| | | 25 | | /// <param name="notificationPublisher">Optional publisher; when null, validation still runs but no notification |
| | | 26 | | /// <param name="errors">Optional explicit errors; when null, uses errors from <see cref="IValidationBehavior"/> |
| | | 27 | | /// <returns><see langword="true"/> when validation succeeds; otherwise <see langword="false"/>.</returns> |
| | | 28 | | public bool TryValidateAndNotify( |
| | | 29 | | INotificationPublisher? notificationPublisher, |
| | | 30 | | IEnumerable<string>? errors = null) |
| | | 31 | | { |
| | 21 | 32 | | if (owner.Validate()) |
| | 12 | 33 | | return true; |
| | | 34 | | |
| | 9 | 35 | | notificationPublisher?.PublishErrors(errors ?? owner.GetValidationErrors()); |
| | | 36 | | |
| | 9 | 37 | | return false; |
| | | 38 | | } |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Gets validation error messages from the registered <see cref="IValidationBehavior"/>, if any. |
| | | 42 | | /// </summary> |
| | | 43 | | public IReadOnlyCollection<string> GetValidationErrors() => |
| | 9 | 44 | | owner.Behaviors.TryGet<IValidationBehavior>(out var behavior) ? behavior.Errors : []; |
| | | 45 | | } |
| | | 46 | | } |
| | | 47 | | |