72 lines
1.9 KiB
C#
72 lines
1.9 KiB
C#
using System.ComponentModel.DataAnnotations;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using System.Text.RegularExpressions;
|
|
|
|
namespace DAL.Values
|
|
{
|
|
[JsonConverter(typeof(PhoneNumberJsonConverter))]
|
|
public partial class PhoneNumber
|
|
{
|
|
[MaxLength(32)] private string _phoneNumber = null!;
|
|
|
|
[JsonIgnore]
|
|
[MaxLength(32)]
|
|
public string value
|
|
{
|
|
get => _phoneNumber;
|
|
set
|
|
{
|
|
if (phoneNumberConfirmation().IsMatch(value))
|
|
{
|
|
_phoneNumber = phoneNumberConfirmation().Replace(value, "$1 ($2) $3-$4");
|
|
_phoneNumber = _phoneNumber.Trim();
|
|
}
|
|
else
|
|
{
|
|
throw new ValidationException("Phone number is invalid");
|
|
}
|
|
}
|
|
}
|
|
|
|
public static implicit operator string(PhoneNumber phoneNumber)
|
|
{
|
|
return phoneNumber.value;
|
|
}
|
|
public static implicit operator PhoneNumber(string str)
|
|
{
|
|
return new PhoneNumber { value = str };
|
|
}
|
|
|
|
// https://www.abstractapi.com/guides/phone-validation/c-validate-phone-number
|
|
[GeneratedRegex(@"^([+]?[0-9]{1,3})?[-. ]?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$")]
|
|
public static partial Regex phoneNumberConfirmation();
|
|
}
|
|
|
|
public class PhoneNumberJsonConverter : JsonConverter<PhoneNumber>
|
|
{
|
|
public override PhoneNumber? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
|
{
|
|
string? phoneNumber = reader.GetString();
|
|
if (phoneNumber != null)
|
|
{
|
|
if (!PhoneNumber.phoneNumberConfirmation().IsMatch(phoneNumber))
|
|
{
|
|
throw new JsonException("Phone number invalid. Match '^([+]?[0-9]{1,3})?[-. ]?\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$'");
|
|
}
|
|
|
|
return new PhoneNumber
|
|
{
|
|
value = phoneNumber
|
|
};
|
|
}
|
|
|
|
throw new JsonException("Expected string for PhoneNumber deserialization.");
|
|
}
|
|
public override void Write(Utf8JsonWriter writer, PhoneNumber value, JsonSerializerOptions options)
|
|
{
|
|
writer.WriteStringValue(value);
|
|
}
|
|
}
|
|
}
|