aruni
aruni

Reputation: 2752

How to validate the phone no?

I'm using MVC and I want to validate the phone No

I wrote this class:

public class StudentValidator : AbstractValidator<graduandModel>
{
    public StudentValidator(ILocalizationService localizationService)
    {
        RuleFor(x => x.phone).NotEmpty().WithMessage(localizationService.GetResource("Hire.HireItem.Fields.phone.Required"));
    }
}

How can I validate the phone number inside this class?

Can I use the following?

RuleFor(x => x.phone).SetValidator(....)

If so how can I use it??

Upvotes: 4

Views: 15111

Answers (5)

mariusz96
mariusz96

Reputation: 128

You can also write an adapter for DataAnnotations:

public static class RuleBuilderExtensions
{
    public static IRuleBuilderOptions<T, string> Phone<T>(this IRuleBuilder<T, string> ruleBuilder)
    {
        return ruleBuilder.SetValidator(new PhoneValidator<T>());
    }
}

public class PhoneValidator<T> : PropertyValidator<T, string>
{
    private static readonly PhoneAttribute PhoneAttribute = new PhoneAttribute();

    public override bool IsValid(ValidationContext<T> context, string value)
    {
        // Automatically pass if value is null.
        // NotEmpty should be used to assert a value is not null.
        if (value is null)
        {
            return true;
        }

        return PhoneAttribute.IsValid(value);
    }

    public override string Name => "PhoneValidator";

    protected override string GetDefaultMessageTemplate(string errorCode)
        => "'{PropertyName}' is not a valid phone number.";
}

Upvotes: 0

anakic
anakic

Reputation: 2978

Other answers here discuss how to apply validation. As for implementing the validation logic, I'd recommend using a library like libphonenumber-csharp rather than rolling your own logic or using a regex.

Phone numbers are extremely tricky to validate if you want to accept phone numbers from many countries.

Here's an example snippet for validating a US phone number using libphonenumber-csharp:

using PhoneNumbers;

var phoneNumberUtil = PhoneNumberUtil.GetInstance();
var phoneNumber = phoneNumberUtil.Parse("+14156667777", "US");
var isValid = phoneNumberUtil.IsValidNumber(phoneNumber);

Console.WriteLine(isValid); // true

The library supports local and international number formats and all countries.

The NuGet page for this library is here.

I am not affiliated with the library or its authors in any way.

Upvotes: 1

user16985814
user16985814

Reputation:

the code sample below uses fluent validation for phone number validation

  class StudentCommandValidation :  AbstractValidator<StudentCommand>
{
    public StudentCommandValidation()
    {
        RuleFor(p => p.PhoneNumber)
       .NotEmpty()
       .NotNull().WithMessage("Phone Number is required.")
       .MinimumLength(10).WithMessage("PhoneNumber must not be less than 10 characters.")
       .MaximumLength(20).WithMessage("PhoneNumber must not exceed 50 characters.")
       .Matches(new Regex(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}")).WithMessage("PhoneNumber not valid");
    }
}

Upvotes: 9

Yannick Blondeau
Yannick Blondeau

Reputation: 9621

Have you considered using DataAnnotations in your model?

Something like this:

[DataType(DataType.PhoneNumber, ErrorMessage = "Invalid Phone Number")]
public string PhoneNumber { get; set; }

Another solution would be the use of regular expressions:

[DisplayName("Phone number")]
[Required(ErrorMessage = "Phone number is required")]
[RegularExpression(@"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}", ErrorMessage = "Invalid phone number")]

Upvotes: 5

Irakli Lekishvili
Irakli Lekishvili

Reputation: 34158

You need regular expression.

Try this examples

Regex Library

and then you can use regex pattern in data anotations like this:

[RegularExpression(@"^[2-9]\d{2}-\d{3}-\d{4}$", ErrorMessage = "Please enter a valid phone number.")]
public string PhoneNumber { get; set; }

Upvotes: 3

Related Questions