Skip to main content

Validation

Overview

ASOL.Core.Validation provides reusable validation helpers focused on phone number validation. The package exposes validation attributes for model properties and extension methods for custom validation implemented through IValidatableObject.

Install

  • ASOL.Core.Validation

Usage third party libraries (NuGets)

Usage

The recommended entry point is PhoneNumberStrictAttribute. It uses libphonenumber-csharp and validates international phone numbers in a stricter way than the older PhoneNumberAttribute.

using ASOL.Core.Validation;
using System.ComponentModel.DataAnnotations;

public class ContactDto
{
[PhoneNumberStrict]
public string? PhoneNumber { get; set; }
}

null and empty string are treated as valid values. The validator expects an international format with country prefix, for example:

  • +420606123123
  • +420 606 123 123
  • +421907149209
  • +421 907 149 209

Examples that are rejected:

  • 606123123
  • 606 123 123
  • 00420 606 123 123
  • +420

If you implement custom validation through IValidatableObject, use the extension method ValidatePhoneNumberStrict.

using ASOL.Core.Validation;
using System.ComponentModel.DataAnnotations;

public class ContactDto : IValidatableObject
{
public string? PhoneNumber { get; set; }

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
return this.ValidatePhoneNumberStrict(PhoneNumber);
}
}

Error messages

By default, the package returns a localized message from embedded resources:

  • Neplatné telefonní číslo.

You can override the message directly:

[PhoneNumberStrict("Invalid contact phone number.")]
public string? PhoneNumber { get; set; }

PhoneNumberAttribute and ValidatePhoneNumber(...) are still available for backward compatibility, but both are marked as obsolete. Prefer the strict variants for new code.