Build a custom .NET validation attribute

Web forms often fail at the boundary between what a browser accepts and what a server can trust. Required fields, masks and input types improve the experience, but users can bypass them and older clients can send anything. ASP.NET Core therefore has to validate request data again at the server boundary.

DataAnnotations already supply useful building blocks such as Required, EmailAddress, StringLength and Range. Creating a custom .NET attribute for input validation is worthwhile when a business rule appears across several request types or needs a clear contract of its own. An Australian mobile number is a practical example because local 04 numbers and +61 forms are common, yet the underlying rule remains specific.

This walkthrough builds an AustralianMobileNumber attribute for ASP.NET Core, applies it to a request DTO and covers the tests that matter. In an Angular application, a time-based Angular caching service can keep cached reference data fresh, but it cannot determine whether a value submitted to the API is valid. The server remains the enforcement point.

Why a custom attribute belongs in the model

Keeping a rule on the request DTO gives it a stable home. The runtime reads attribute metadata during model binding and validation, then adds failures to ModelState. Controllers can stay focused on the use case, while the same attribute can protect a contact form, a customer profile and another endpoint without duplicating the rule.

Validation should answer a narrow question: is this value allowed under the agreed contract? It is not output encoding, SQL-injection protection or a reason to delete suspicious characters. A missing email annotation can be rejected, while a script-like name may still need safe handling when rendered. Parameterised database access and context-aware output encoding remain separate controls. When a rule spans several properties or needs database access, a dedicated validation library may be clearer than attribute metadata.

That separation is particularly helpful in Australian product teams. Sydney and Melbourne are major centres for fintech, logistics and SaaS, where .NET and Azure stacks are common, while Brisbane has a growing developer market. Australian checkouts also need to apply the 10% GST using decimal arithmetic, so server-side rules remain useful even when the browser calculates a total. A local team may call a reusable validator a “keen” addition during stand-up, but the implementation still needs a precise rule and trustworthy tests.

Define the rule before writing the regex

Define the contract before choosing a regular expression. This validator will accept an Australian mobile number written as ten local digits beginning with 04, or in international form beginning with +61 and containing nine digits after the country code. Spaces, brackets and hyphens may appear for readability. Letters, unexpected punctuation, extensions and service numbers such as 1300 will be rejected.

Decide whether null is valid. Returning success for null makes the attribute composable: use Required when the field is mandatory, and omit that annotation when it is optional. An empty string is different from null and should fail the mobile-number rule. This keeps presence validation and format validation as separate concerns.

Also separate validation from canonical storage. The input might arrive as 0412 345 678, but a downstream SMS service may expect +61412345678. Store the original string in the DTO if that is your policy, validate a temporary compact form, then normalise it in a mapper once validation succeeds. A validation attribute should report whether a value is acceptable, not quietly rewrite it.

Local conventions deserve similar care. Australian users often read dates as dd/MM/yyyy, and the country spans several time zones with daylight-saving changes in most states. Keep API timestamps in UTC and do not force one local time onto an unrelated validator. Although “no worries” is a common Australian response, a validation message should still identify the problem, accepted examples and the field that needs attention.

Implement the attribute for ASP.NET Core

The custom attribute can derive from ValidationAttribute and return a ValidationResult when the value fails the mobile-number contract.

using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

[AttributeUsage(
    AttributeTargets.Property | AttributeTargets.Field,
    AllowMultiple = false)]
public sealed class AustralianMobileNumberAttribute : ValidationAttribute
{
    private static readonly Regex Formatting = new(
        @"[\s()\-]",
        RegexOptions.Compiled | RegexOptions.CultureInvariant);

    private static readonly Regex MobilePattern = new(
        @"\A(?:\+61|0)4\d{8}\z",
        RegexOptions.Compiled | RegexOptions.CultureInvariant);

    public AustralianMobileNumberAttribute()
    {
        ErrorMessage =
            "Enter a valid Australian mobile number, such as " +
            "0412 345 678 or +61 412 345 678.";
    }

    protected override ValidationResult? IsValid(
        object? value,
        ValidationContext validationContext)
    {
        if (value is null)
        {
            return ValidationResult.Success;
        }

        var members = validationContext.MemberName is { } name
            ? new[] { name }
            : Array.Empty<string>();

        if (value is not string candidate)
        {
            return new ValidationResult(
                FormatErrorMessage(validationContext.DisplayName),
                members);
        }

        var compact = Formatting.Replace(candidate.Trim(), string.Empty);

        if (MobilePattern.IsMatch(compact))
        {
            return ValidationResult.Success;
        }

        return new ValidationResult(
            FormatErrorMessage(validationContext.DisplayName),
            members);
    }
}

The attribute returns success for null so Required can control presence. It removes only approved formatting characters for the check, leaving letters and other unexpected content visible to the pattern. The anchored expression prevents a valid prefix or suffix from sneaking through. Since the original value is never changed, canonicalisation remains a separate mapping decision.

Apply the attribute where the request data enters the application, rather than scattering phone checks throughout a controller.

using System.ComponentModel.DataAnnotations;

public sealed class EnquiryRequest
{
    [Required]
    [StringLength(80)]
    public string Name { get; init; } = string.Empty;

    [Required]
    [EmailAddress]
    public string Email { get; init; } = string.Empty;

    [AustralianMobileNumber]
    [StringLength(32)]
    public string? Mobile { get; init; }
}

With [ApiController], ASP.NET Core evaluates the DTO after model binding and returns a 400 ValidationProblemDetails response when validation fails. The action is reached only when the model is valid, so the controller does not need to repeat the mobile-number check.

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/enquiries")]
public sealed class EnquiriesController : ControllerBase
{
    [HttpPost]
    public IActionResult Create([FromBody] EnquiryRequest request)
    {
        return Accepted(new { requestId = Guid.NewGuid() });
    }
}

Patterns and checks for production forms

The implementation is small, but its conventions matter. Use these rules when adding similar attributes:

Then test both the attribute and the endpoint behaviour:

An Angular form can mirror the accepted pattern with Validators.pattern or native browser constraints, which gives users immediate feedback. The duplicated rule must still match the server, so publish accepted examples and error wording as part of the API contract. Server validation remains authoritative even when the client is current and cooperating.

Australian contact and marketing forms also require separate consent handling under privacy and anti-spam expectations, including the Australian Privacy Act and the ACMA-administered Spam Act. A correctly formatted mobile number says nothing about whether the person has agreed to receive a message.

Ship the validated endpoint with confidence

Attribute-based validation gives each request DTO a compact, visible contract. Built-in annotations handle common constraints, the custom attribute owns the mobile-number rule and ModelState carries failures into a consistent API response. The controller can focus on the enquiry workflow without repeating business rules or trusting browser validation.

Document the accepted forms, null behaviour and error response so frontend developers, QA engineers and support colleagues can exercise the same contract. That shared vocabulary matters when a release is coordinated across teams in Melbourne and Perth, where the working day may start at different times. It also prevents a frontend pattern from drifting away from the server implementation.

Create the attribute in a shared validation project, add the xUnit cases beside it and wire it into the next public request DTO. Publish the accepted formats with the API contract, then have frontend and QA colleagues exercise the same examples before release. Start with the code above and make the server the final authority for every Australian mobile number your product accepts.