skwasjer / IbanNet

C# .NET IBAN validator, parser, builder and generator
Apache License 2.0
119 stars 31 forks source link

feat(validator): move normalization to parser, such that validator is always validating strictly #95

Closed skwasjer closed 1 year ago

skwasjer commented 1 year ago

Move normalization to parser, such that validator is always validating strict.

Add Strict-property (default true) to IbanAttribute and FluentIbanValidator<T> and its associated Iban rule extension. When Strict=true, the input must strictly match the IBAN format rules. When Strict=false, whitespace is ignored and strict character casing enforcement is disabled (meaning, the user can input in lower and uppercase).

This mode is a bit more forgiving when dealing with user-input. However it does require after successful validation, that you parse the user input with IIbanParser to normalize/sanitize the input and to be able to format the IBAN in correct electronic format.

Strict defaults to true.

See #93

Examples:

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

// FluentValidation
public class InputModelValidator : AbstractValidator<InputModel>
{
    public InputModelValidator(IIbanValidator ibanValidator)
    {
        RuleFor(x => x.BankAccountNumber).NotNull().Iban(ibanValidator, strict: false);
    }
}

With validator/parser directly:

// Given that inputStr is "NL91 ABNA 0417 1643 00" or "nl91abna0417164300";

var validator = new IbanValidator();                  // Always strict now.
Console.Write(validator.Validate(inputStr).IsValid)   // false

var parser = new IbanParser(IbanRegistry.Default);    // Always non-strict (as it was before)
Console.Write(parser.TryParse(inputStr, out _));      // true
sonarcloud[bot] commented 1 year ago

Kudos, SonarCloud Quality Gate passed!    Quality Gate passed

Bug A 0 Bugs
Vulnerability A 0 Vulnerabilities
Security Hotspot A 0 Security Hotspots
Code Smell A 0 Code Smells

100.0% 100.0% Coverage
0.0% 0.0% Duplication