Ejemplo n.º 1
0
        /// <summary>
        /// Validates the specified IBAN for correctness.
        /// </summary>
        /// <param name="iban">The IBAN value.</param>
        /// <returns>a validation result, indicating if the IBAN is valid or not</returns>
        public ValidationResult Validate(string iban)
        {
            InitRegistry();

            string normalizedIban = Iban.Normalize(iban);
            var    context        = new ValidationContext
            {
                Value   = normalizedIban,
                Result  = IbanValidationResult.Valid,
                Country = GetMatchingCountry(normalizedIban)
            };

            foreach (IIbanValidationRule rule in _rules)
            {
                rule.Validate(context);
                if (context.Result != IbanValidationResult.Valid)
                {
                    break;
                }
            }

            return(new ValidationResult
            {
                Value = normalizedIban?.ToUpperInvariant(),
                Result = context.Result,
                Country = context.Country
            });
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Validates the specified IBAN for correctness.
        /// </summary>
        /// <param name="iban">The IBAN value.</param>
        /// <returns>a validation result, indicating if the IBAN is valid or not</returns>
        public ValidationResult Validate(string?iban)
        {
            string?normalizedIban = Iban.NormalizeOrNull(iban);

            var context          = new ValidationRuleContext(normalizedIban ?? string.Empty);
            var validationResult = new ValidationResult
            {
                AttemptedValue = normalizedIban
            };

            foreach (IIbanValidationRule rule in _rules)
            {
                try
                {
                    validationResult.Error = rule.Validate(context) as ErrorResult;
                }
#pragma warning disable CA1031 // Do not catch general exception types - justification: custom rules can throw unexpected exceptions. We handle it with ExceptionResult.
                catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
                {
                    validationResult.Error = new ExceptionResult(ex);
                }

                if (!validationResult.IsValid)
                {
                    break;
                }
            }

            validationResult.Country = context.Country;
            return(validationResult);
        }
Ejemplo n.º 3
0
            public void It_should_normalize(string iban, string expected)
            {
                // Act
                var actual = new Iban(iban);

                // Assert
                actual.ToString().Should().Be(expected);
            }
Ejemplo n.º 4
0
            public When_comparing_for_inequality()
            {
                var ibanParser = new IbanParser(IbanValidatorMock.Object);

                _iban      = ibanParser.Parse(TestValues.ValidIban);
                _equalIban = ibanParser.Parse(TestValues.ValidIbanPartitioned);
                _otherIban = ibanParser.Parse("AE070331234567890123456");
            }
Ejemplo n.º 5
0
            public void With_null_value_should_throw()
            {
                // Act
                Action act = () => Iban.Parse(null);

                // Assert
                act.Should().Throw <ArgumentNullException>("the provided value was null").Which.ParamName.Should().Be("value");
            }
Ejemplo n.º 6
0
            public override void SetUp()
            {
                base.SetUp();

                _iban      = Iban.Parse(TestValues.ValidIban);
                _equalIban = Iban.Parse(TestValues.ValidIbanPartitioned);
                _otherIban = Iban.Parse("AE070331234567890123456");
            }
Ejemplo n.º 7
0
            public void With_null_value_should_return_false()
            {
                // Act
                bool actual = Iban.TryParse(null, out Iban iban);

                // Assert
                actual.Should().BeFalse("the provided value was null which is not valid");
                iban.Should().BeNull("parsing did not succeed");
            }
Ejemplo n.º 8
0
            public void With_invalid_value_should_throw()
            {
                // Act
                Action act = () => Iban.Parse(TestValues.InvalidIban);

                // Assert
                act.ShouldThrow <IbanFormatException>("the provided value was invalid")
                .Which.Result
                .Should().Be(IbanValidationResult.IllegalCharacters);
            }
Ejemplo n.º 9
0
            public void By_reference_when_other_is_null_should_return_false()
            {
                Iban nullIban = null;

                // Act
                // ReSharper disable once AssignNullToNotNullAttribute
                bool actual = _iban.Equals(nullIban);

                // Assert
                actual.Should().BeFalse();
            }
Ejemplo n.º 10
0
            public void With_invalid_value_should_return_false()
            {
                // Act
                bool actual = Iban.TryParse(TestValues.InvalidIban, out Iban iban);

                // Assert
                actual.Should().BeFalse("the provided value was invalid");
                iban.Should().BeNull("parsing did not succeed");

                IbanValidatorMock.Verify(m => m.Validate(It.IsAny <string>()), Times.Once);
            }
Ejemplo n.º 11
0
            public void It_should_be_same_as_underlying_string_value()
            {
                var iban             = new Iban(TestValues.ValidIban);
                int expectedHashCode = TestValues.ValidIban.GetHashCode();

                // Act
                int actual = iban.GetHashCode();

                // Assert
                actual.Should().Be(expectedHashCode);
            }
Ejemplo n.º 12
0
            public void With_value_that_causes_custom_rule_to_throw_should_rethrow()
            {
                // Act
                Action act = () => Iban.Parse(TestValues.IbanForCustomRuleException);

                // Assert
                IbanFormatException ex = act.Should().Throw <IbanFormatException>("the provided value was invalid").Which;

                ex.Result.Should().BeNull();
                ex.InnerException.Should().NotBeNull();
                ex.Message.Should().Contain("is not a valid IBAN.");
            }
Ejemplo n.º 13
0
        public void When_iban_contains_whitespace_should_validate(string ibanWithWhitespace)
        {
            // Act
            ValidationResult actual = _validator.Validate(ibanWithWhitespace);

            // Assert
            actual.Should().BeEquivalentTo(new ValidationResult
            {
                Value   = Iban.Normalize(ibanWithWhitespace),
                Result  = IbanValidationResult.Valid,
                Country = _countryValidationSupport.SupportedCountries["NL"]
            });
        }
Ejemplo n.º 14
0
            public void With_valid_value_should_pass()
            {
                // Act
                var actual = Iban.TryParse(TestValues.ValidIban, out var iban);

                // Assert
                actual.Should().BeTrue("the provided value was valid");
                iban.Should().NotBeNull().
                And.BeOfType <Iban>()
                .Which.ToString()
                .Should().Be(TestValues.ValidIban);

                _ibanValidatorMock.Verify(m => m.Validate(It.IsAny <string>()), Times.Once);
            }
Ejemplo n.º 15
0
            public void With_valid_value_should_return_iban()
            {
                Iban iban = null;

                // Act
                Action act = () => iban = Iban.Parse(TestValues.ValidIban);

                // Assert
                act.ShouldNotThrow <IbanFormatException>();
                iban.Should().NotBeNull("the value should be parsed")
                .And.BeOfType <Iban>()
                .Which.ToString()
                .Should().Be(TestValues.ValidIban, "the returned value should match the provided value");
            }
Ejemplo n.º 16
0
            public void With_value_that_fails_custom_rule_should_throw()
            {
                // Act
                Action act = () => Iban.Parse(TestValues.IbanForCustomRuleFailure);

                // Assert
                IbanFormatException ex = act.Should().Throw <IbanFormatException>("the provided value was invalid").Which;

                ex.Result.Should().BeEquivalentTo(new ValidationResult
                {
                    Error          = new ErrorResult("Custom message"),
                    AttemptedValue = TestValues.IbanForCustomRuleFailure
                });
                ex.InnerException.Should().BeNull();
                ex.Message.Should().Be("Custom message");
            }
Ejemplo n.º 17
0
            public void With_invalid_value_should_throw()
            {
                // Act
                Action act = () => Iban.Parse(TestValues.InvalidIban);

                // Assert
                IbanFormatException ex = act.Should().Throw <IbanFormatException>("the provided value was invalid").Which;

                ex.Result.Should().BeEquivalentTo(new ValidationResult
                {
                    Error          = new IllegalCharactersResult(),
                    AttemptedValue = TestValues.InvalidIban
                });
                ex.InnerException.Should().BeNull();
                ex.Message.Should().Be("The IBAN contains illegal characters.");
            }
Ejemplo n.º 18
0
        /// <summary>
        /// Validates the specified IBAN for correctness.
        /// </summary>
        /// <param name="iban">The IBAN value.</param>
        /// <returns>a validation result, indicating if the IBAN is valid or not</returns>
        public IbanValidationResult Validate(string iban)
        {
            var normalizedIban = Iban.Normalize(iban);

            var validationResult = IbanValidationResult.Valid;

            foreach (var rule in Rules)
            {
                validationResult = rule.Validate(normalizedIban);
                if (validationResult != IbanValidationResult.Valid)
                {
                    break;
                }
            }
            return(validationResult);
        }
Ejemplo n.º 19
0
        /// <inheritdoc />
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            switch (value)
            {
            case null:
                return(null);

            case string strValue:
                if (Iban.TryParse(strValue, out var iban))
                {
                    return(iban);
                }

                break;
            }

            return(base.ConvertFrom(context, culture, value));
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Attempts to parse the specified <paramref name="value"/> into an <see cref="Iban"/>.
        /// </summary>
        /// <param name="value">The IBAN value to parse.</param>
        /// <param name="iban">The <see cref="Iban"/> if the <paramref name="value"/> is parsed successfully.</param>
        /// <param name="validationResult">The validation result.</param>
        /// <returns>true if the <paramref name="value"/> is parsed successfully, or false otherwise</returns>
        private static bool TryParse(string value, out Iban iban, out IbanValidationResult validationResult)
        {
            iban             = null;
            validationResult = IbanValidationResult.IllegalCharacters;
            if (value == null)
            {
                return(false);
            }

            var normalizedValue = Normalize(value);

            if ((validationResult = Validator.Validate(normalizedValue)) == IbanValidationResult.Valid)
            {
                iban = new Iban(normalizedValue.ToUpperInvariant());
                return(true);
            }

            return(false);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Attempts to parse the specified <paramref name="value"/> into an <see cref="Iban"/>.
        /// </summary>
        /// <param name="value">The IBAN value to parse.</param>
        /// <param name="iban">The <see cref="Iban"/> if the <paramref name="value"/> is parsed successfully.</param>
        /// <param name="validationResult">The validation result.</param>
        /// <returns>true if the <paramref name="value"/> is parsed successfully, or false otherwise</returns>
        private static bool TryParse(string value, out Iban iban, out IbanValidationResult validationResult)
        {
            iban             = null;
            validationResult = IbanValidationResult.IllegalCharacters;
            if (value == null)
            {
                return(false);
            }

            // Although our validator normalizes too, we can't rely on this fact if other implementations
            // are provided (like mocks, or maybe faster validators). Thus, to ensure this class correctly
            // represents the IBAN value, we normalize inline here and take the penalty.
            string           normalizedValue = Normalize(value);
            ValidationResult result          = Validator.Validate(normalizedValue);

            if (result.Result == IbanValidationResult.Valid)
            {
                iban = new Iban(normalizedValue.ToUpperInvariant());
                return(true);
            }

            return(false);
        }
Ejemplo n.º 22
0
            public override void SetUp()
            {
                base.SetUp();

                _iban = Iban.Parse(TestValues.ValidIban);
            }
Ejemplo n.º 23
0
 private bool Equals(Iban other)
 {
     return(string.Equals(_iban, other._iban));
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Attempts to parse the specified <paramref name="value"/> into an <see cref="Iban"/>.
        /// </summary>
        /// <param name="value">The IBAN value to parse.</param>
        /// <param name="iban">The <see cref="Iban"/> if the <paramref name="value"/> is parsed successfully.</param>
        /// <returns>true if the <paramref name="value"/> is parsed successfully, or false otherwise</returns>
        public static bool TryParse(string value, out Iban iban)
        {
            iban = null;

            return(TryParse(value, out iban, out var _));
        }
Ejemplo n.º 25
0
 public When_formatting()
 {
     _iban = new Iban(TestValues.ValidIban);
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Attempts to parse the specified <paramref name="value"/> into an <see cref="Iban"/>.
        /// </summary>
        /// <param name="value">The IBAN value to parse.</param>
        /// <param name="iban">The <see cref="Iban"/> if the <paramref name="value"/> is parsed successfully.</param>
        /// <returns>true if the <paramref name="value"/> is parsed successfully, or false otherwise</returns>
        public static bool TryParse(string value, out Iban iban)
        {
            iban = null;

            return(TryParse(value, out iban, out IbanValidationResult _));
        }