Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

UsernamePropertyValidator.cs

using System.Text.RegularExpressions;
using FluentValidation;
using FluentValidation.Validators;
using Nop.Core.Domain.Customers;

namespace Nop.Web.Framework.Validators;

/// 
/// Username validator
/// 
public partial class UsernamePropertyValidator : PropertyValidator
{
    protected readonly CustomerSettings _customerSettings;

    public override string Name => "UsernamePropertyValidator";

    /// 
    /// Ctor
    /// 
    public UsernamePropertyValidator(CustomerSettings customerSettings)
    {
        _customerSettings = customerSettings;
    }

    /// 
    /// Is valid?
    /// 
    /// Validation context
    /// Result
    public override bool IsValid(ValidationContext context, TProperty value)
    {
        return IsValid(value as string, _customerSettings);
    }

    /// 
    /// Is valid?
    /// 
    /// Username
    /// Customer settings
    /// Result
    public static bool IsValid(string username, CustomerSettings customerSettings)
    {
        if (!customerSettings.UsernameValidationEnabled || string.IsNullOrEmpty(customerSettings.UsernameValidationRule))
            return true;

        if (string.IsNullOrEmpty(username))
            return false;

        return customerSettings.UsernameValidationUseRegex
            ? Regex.IsMatch(username, customerSettings.UsernameValidationRule, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)
            : username.All(l => customerSettings.UsernameValidationRule.Contains(l));
    }

    protected override string GetDefaultMessageTemplate(string errorCode) => "Username is not valid";
}