Skip to content

IbanNet.DataAnnotations

Martijn Bodeman edited this page Aug 10, 2023 · 17 revisions

The IbanNet.DataAnnotations package provides support to validate IBAN user input with Microsoft DataAnnotations.

Usage

By property

public class InputModel
{
    [Iban(Strict = true)]
    [Required]
    public string BackAccountNumber { get; set; }
}

// MVC
public class MyMvcController : Controller
{
    [HttpPost]
    public ActionResult Save(InputModel model)
    {
        if (ModelState.IsValid)
        {
            // ..
        }
    }
}

// Web API
public class MyWebApiController : ApiController
{
    [HttpPost]
    public IHttpActionResult Save(InputModel model)
    {
        if (ModelState.IsValid)
        {
            // ..
        }
    }
}

By parameter

public class MyController : Controller
{
    [HttpPost]
    public ActionResult Save([Required][Iban] string bankAccountNumber)
    {
        if (ModelState.IsValid)
        {
            // ..
        }
    }
}

Note that model validation by parameter is not supported by every version of ASP.NET Core. If you experience problems, use a complex model and a property instead (see above).

Strict

By default, IBAN's submitted to the validator will be validated strictly according to the ISO 13616 specification (if using the SWIFT registry provider). If you wish to allow more relaxed validation that ignores casing rules and whitespace in the user input, set the Strict boolean on the attribute to false. It is however recommended that if you do so, to use the IbanParser to parse the value further down in your application code to ensure it is fully conformant to the ISO 13616 specification.

Not required

The IbanAttribute does not require a property to be set, and as such a null value will be validated successfully. An empty string property however IS considered invalid. To disallow null values add the RequiredAttribute.

Dependency injection

The System.ComponentModel.DataAnnotations.ValidationContext provides an IServiceProvider for resolving dependencies. IbanNet uses this to resolve an IIbanValidator which is then used to validate the user input. If no instance of IIbanValidator can be resolved from the IoC container an exception is thrown.

Additional info

For more detailed info please visit: