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).

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: