Webiant Logo Webiant Logo
  1. No results found.

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

PhoneNumberPropertyValidator.cs

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

namespace Nop.Web.Framework.Validators;

/// 
/// Phohe number validator
/// 
public partial class PhoneNumberPropertyValidator : PropertyValidator
{
    protected readonly CustomerSettings _customerSettings;

    public override string Name => "PhoneNumberPropertyValidator";

    /// 
    /// Ctor
    /// 
    public PhoneNumberPropertyValidator(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?
    /// 
    /// Phone number
    /// Customer settings
    /// Result
    public static bool IsValid(string phoneNumber, CustomerSettings customerSettings)
    {
        if (!customerSettings.PhoneNumberValidationEnabled || string.IsNullOrEmpty(customerSettings.PhoneNumberValidationRule))
            return true;

        if (string.IsNullOrEmpty(phoneNumber))
        {
            return !customerSettings.PhoneRequired;
        }

        return customerSettings.PhoneNumberValidationUseRegex
            ? Regex.IsMatch(phoneNumber, customerSettings.PhoneNumberValidationRule, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)
            : phoneNumber.All(l => customerSettings.PhoneNumberValidationRule.Contains(l));
    }

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