64 lines
1.7 KiB
C#
64 lines
1.7 KiB
C#
using FluentValidation;
|
|
|
|
namespace cuqmbr.TravelGuide.Application.Common.FluentValidation;
|
|
|
|
public static class CustomValidators
|
|
{
|
|
public static IRuleBuilderOptions<T, string> IsUsername<T>(
|
|
this IRuleBuilder<T, string> ruleBuilder)
|
|
{
|
|
return
|
|
ruleBuilder
|
|
.Matches(@"^[a-z0-9-_.]*$");
|
|
}
|
|
|
|
// According to RFC 5321.
|
|
public static IRuleBuilderOptions<T, string> IsEmail<T>(
|
|
this IRuleBuilder<T, string> ruleBuilder)
|
|
{
|
|
return
|
|
ruleBuilder
|
|
.Matches(@"^[\w\.-]{1,64}@[\w\.-]{1,251}\.\w{2,4}$");
|
|
}
|
|
|
|
// According to ITU-T E.164, no spaces.
|
|
public static IRuleBuilderOptions<T, string> IsPhoneNumber<T>(
|
|
this IRuleBuilder<T, string> ruleBuilder)
|
|
{
|
|
return
|
|
ruleBuilder
|
|
.Matches(@"^\+[0-9]{7,15}$");
|
|
}
|
|
|
|
public static IRuleBuilderOptions<T, ICollection<TSource>>
|
|
IsUnique<T, TSource, TResult>(
|
|
this IRuleBuilder<T, ICollection<TSource>> ruleBuilder,
|
|
Func<TSource, TResult> selector)
|
|
{
|
|
if (selector == null)
|
|
{
|
|
throw new ArgumentNullException(
|
|
nameof(selector),
|
|
"Cannot pass a null selector.");
|
|
}
|
|
|
|
return
|
|
ruleBuilder
|
|
.Must(x => x.IsDistinct(selector));
|
|
}
|
|
|
|
public static bool IsDistinct<TSource, TResult>(
|
|
this IEnumerable<TSource> elements, Func<TSource, TResult> selector)
|
|
{
|
|
var hashSet = new HashSet<TResult>();
|
|
foreach (var element in elements.Select(selector))
|
|
{
|
|
if (!hashSet.Contains(element))
|
|
hashSet.Add(element);
|
|
else
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
}
|