using FluentValidation; using Raven.Client.Documents; using Raven.Client.Documents.Session; using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using zero.Core.Api; using zero.Core.Entities; namespace zero.Core.Extensions { public static class ValidatorExtensions { private const char DOT = '.'; private const char KLAMMERAFFE = '@'; private static string HEX_REGEX = "#[0-9a-fA-F]{3,8}"; /// /// Validate a color input as HEX (#aabbccdd or #aabbcc or #abc) /// public static IRuleBuilderOptions Hex(this IRuleBuilder ruleBuilder) { return ruleBuilder.Matches(HEX_REGEX).WithMessage("@errors.forms.hex_format"); } /// /// Validate an email /// public static IRuleBuilderOptions Url(this IRuleBuilder ruleBuilder) { return ruleBuilder.Must((root, value, context) => { return value.IsNullOrWhiteSpace() || Uri.IsWellFormedUriString(value, UriKind.Absolute); }).WithMessage("@errors.forms.url_format"); } /// /// Validate an email /// public static IRuleBuilderOptions Email(this IRuleBuilder ruleBuilder) { return ruleBuilder.Must((root, value, context) => { if (value.IsNullOrWhiteSpace()) { return true; } int index = value.IndexOf(KLAMMERAFFE); if (index < 0 || index == value.Length - 1 || index != value.LastIndexOf(KLAMMERAFFE)) { return false; } return true; }).WithMessage("@errors.forms.email_invalid"); } /// /// Validate one or multiple emails /// public static IRuleBuilderOptions Emails(this IRuleBuilder ruleBuilder) { return ruleBuilder.Must((root, value, context) => { if (value.IsNullOrWhiteSpace()) { return true; } string[] mails = value.Split(',', ';').Select(x => x.Trim()).Where(x => !x.IsNullOrWhiteSpace()).ToArray(); if (!mails.Any()) { return false; } foreach (string mail in mails) { int index = value.IndexOf(KLAMMERAFFE); if (index < 0 || index == value.Length - 1 || index != value.LastIndexOf(KLAMMERAFFE)) { return false; } } return true; }).WithMessage("@errors.forms.emails_invalid"); } /// /// Check if this value is unique within a collection /// public static IRuleBuilderOptions Unique(this IRuleBuilder ruleBuilder, IBackofficeStore store) where T : IZeroIdEntity { return ruleBuilder.MustAsync(async (entity, value, context, cancellation) => { bool includeShared = typeof(IAppAwareShareableEntity).IsAssignableFrom(typeof(T)); using IAsyncDocumentSession session = store.Raven.OpenAsyncSession(); bool any = await session.Advanced.AsyncDocumentQuery() .Scope(store.AppContext.AppId, includeShared) .WhereNotEquals(nameof(IZeroIdEntity.Id), entity.Id) .WhereEquals(context.Rule.PropertyName.ToPascalCaseId(), value) .AnyAsync(cancellation); return !any; }).WithMessage("@errors.forms.not_unique"); } } }