Skip to content

Commit

Permalink
Add phonenumberlib for enhanced number validation #14
Browse files Browse the repository at this point in the history
  • Loading branch information
elektrolytmangel committed Oct 19, 2023
1 parent cf2ea5b commit 41f46fa
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
<ItemGroup>
<PackageReference Include="Azure.Storage.Blobs" Version="12.16.0" />
<PackageReference Include="FluentValidation" Version="11.6.0" />
<PackageReference Include="libphonenumber-csharp" Version="8.13.23" />
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Http" Version="3.2.0" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.2.0" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,57 @@
using DefikarteBackend.Model;
using FluentValidation;
using System.Text.RegularExpressions;

namespace DefikarteBackend.Validation
{
public class DefibrillatorRequestValidator : AbstractValidator<DefibrillatorRequest>
{
private readonly string _phoneNumberPattern = @"^(\+41|0041|0)\s?(\d{2})\s?(\d{3})\s?(\d{2})\s?(\d{2})$";

public DefibrillatorRequestValidator()
{
RuleFor(x => x.Latitude).NotEmpty();
RuleFor(x => x.Longitude).NotEmpty();
RuleFor(x => x.Reporter).NotEmpty();
RuleFor(x => x.Location).NotEmpty().MaximumLength(200);
RuleFor(x => x.Description).MaximumLength(200);
RuleFor(x => x.OperatorPhone).Matches(_phoneNumberPattern).When(x => !string.IsNullOrEmpty(x.OperatorPhone));
RuleFor(x => x.OperatorPhone).Custom((value, context) => PhoneNumberValid(value, context)).When(x => !string.IsNullOrEmpty(x.OperatorPhone));
RuleFor(x => x.Access).NotNull();
RuleFor(x => x.Indoor).NotNull();
RuleFor(x => x.EmergencyPhone).NotEmpty().Matches($"({_phoneNumberPattern})|112|144|117|118|1414");
RuleFor(x => x.EmergencyPhone).NotEmpty().Custom((value, context) => PhoneNumberValid(value, context));
// opening hours validation is missing
}

private void PhoneNumberValid(string phoneNumberRaw, ValidationContext<DefibrillatorRequest> context)
{
if (string.IsNullOrEmpty(phoneNumberRaw))
{
return;
}

var result = Regex.Match(phoneNumberRaw, "112|144|117|118|1414");
if (result.Success)
{
return;
}

var phoneNumberUtil = PhoneNumbers.PhoneNumberUtil.GetInstance();
try
{
var value = phoneNumberUtil.Parse(phoneNumberRaw, "CH");
var valid =
phoneNumberUtil.IsPossibleNumber(value) &&
phoneNumberUtil.IsValidNumber(value) &&
(phoneNumberUtil.IsValidNumberForRegion(value, "CH")
|| phoneNumberUtil.IsValidNumberForRegion(value, "LI"));

if (!valid)
{
context.AddFailure(context.PropertyName, "Phonenumber not valid");
}
}
catch (System.Exception)
{
context.AddFailure(context.PropertyName, "Phonenumber not valid");
}
}
}
}

0 comments on commit 41f46fa

Please sign in to comment.