1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
//! This crate provides an easy way to validate an IBAN (International Bank Account Number). To do //! so, you can use the function [`parse()`](str::parse). This will check the IBAN rules //! as well as the BBAN structure. The provided [`Iban`](crate::Iban) structure provides many methods //! to easy the handling of an IBAN. Many of these methods are provided via the [`IbanLike`](crate::IbanLike) //! trait. //! //! When BBAN parsing fails, the error type [`ParseIbanError`](crate::ParseIbanError) provides useful //! information about what went wrong. Additionally, the error contains [`BaseIban`](crate::BaseIban), //! which can still be used to access useful information. //! //! # Example //! The following example does a full validation of the IBAN and BBAN format. //! //! ```rust //! use iban::*; //! //! let account = "DE44500105175407324931".parse::<Iban>()?; //! //! assert_eq!(account.country_code(), "DE"); //! assert_eq!(account.check_digits(), 44); //! assert_eq!(account.bban(), "500105175407324931"); //! assert_eq!(account.electronic_str(), "DE44500105175407324931"); //! assert_eq!(account.to_string(), "DE44 5001 0517 5407 3249 31"); //! assert_eq!(account.bank_identifier(), Some("50010517")); //! assert_eq!(account.branch_identifier(), None); //! # Ok::<(), iban::ParseIbanError>(()) //! ``` //! //! # Features //! - *serde*: Enable `serde` support for [`Iban`] and [`BaseIban`]. #![doc(html_root_url = "https://docs.rs/iban_validate/3.0.0")] #![forbid(unsafe_code)] #![deny(missing_docs)] #![deny(bare_trait_objects)] #![deny(elided_lifetimes_in_paths)] #![deny(missing_debug_implementations)] use std::convert::TryFrom; use std::fmt; use std::str; use thiserror::Error; use crate::countries::RE_ADDRESS_REMAINDER; use crate::countries::RE_COUNTRY_CODE; mod base_iban; mod countries; #[cfg(test)] mod tests; #[cfg(feature = "serde")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; pub use base_iban::{BaseIban, ParseBaseIbanError}; /// A trait that provide basic functions on an IBAN. It is implemented by both [`Iban`], /// which represents a fully validated IBAN, and [`BaseIban`], which might not have a correct BBAN. pub trait IbanLike { /// Get the IBAN in the electronic format, without whitespace. This method /// is simply a view into the inner string. /// /// # Example /// ```rust /// use iban::*; /// let iban: Iban = "DE44 5001 0517 5407 3249 31".parse()?; /// assert_eq!(iban.electronic_str(), "DE44500105175407324931"); /// # Ok::<(), ParseIbanError>(()) /// ``` fn electronic_str(&self) -> &str; /// Get the country code of the IBAN. This method simply returns a slice of /// the inner representation. /// /// # Example /// ```rust /// use iban::*; /// let iban: Iban = "DE44 5001 0517 5407 3249 31".parse()?; /// assert_eq!(iban.country_code(), "DE"); /// # Ok::<(), ParseIbanError>(()) /// ``` fn country_code(&self) -> &str { &self.electronic_str()[0..2] } /// Get the check digits of the IBAN, as a str. This method simply returns /// a slice of the inner representation. To obtain an integer instead, /// use [`check_digits`](IbanLike::check_digits). /// /// # Example /// ```rust /// use iban::*; /// let iban: Iban = "DE44 5001 0517 5407 3249 31".parse()?; /// assert_eq!(iban.check_digits_str(), "44"); /// # Ok::<(), ParseIbanError>(()) /// ``` fn check_digits_str(&self) -> &str { &self.electronic_str()[2..4] } /// Get the check digits of the IBAN. This method parses the digits to an /// integer, performing slightly more work than [`check_digits_str`](IbanLike::check_digits_str). /// /// # Example /// ```rust /// use iban::*; /// let iban: Iban = "DE44 5001 0517 5407 3249 31".parse()?; /// assert_eq!(iban.check_digits(), 44); /// # Ok::<(), ParseIbanError>(()) /// ``` fn check_digits(&self) -> u8 { self.check_digits_str().parse().expect( "Could not parse check digits. Please create an issue at \ https://github.com/ThomasdenH/iban_validate.", ) } /// Get the BBAN part of the IBAN, as a `&str`. Note that the BBAN is not /// necessarily valid if this is not guaranteed by the implementing type. /// Use [`Iban::bban`] to guarantee a correct BBAN. /// /// # Example /// ```rust /// use iban::*; /// let iban: Iban = "DE44 5001 0517 5407 3249 31".parse()?; /// assert_eq!(iban.bban_unchecked(), "500105175407324931"); /// # Ok::<(), ParseIbanError>(()) /// ``` fn bban_unchecked(&self) -> &str { &self.electronic_str()[4..] } } impl IbanLike for Iban { fn electronic_str(&self) -> &str { self.base_iban.electronic_str() } } impl Iban { /// Get the BBAN part of the IBAN, as a `&str`. This method, in contrast to [`IbanLike::bban_unchecked`], /// is only available on the [`Iban`] structure, which means the returned BBAN string is always correct. /// /// # Example /// ```rust /// use iban::*; /// let iban: Iban = "DE44 5001 0517 5407 3249 31".parse()?; /// assert_eq!(iban.bban(), "500105175407324931"); /// # Ok::<(), ParseIbanError>(()) /// ``` pub fn bban(&self) -> &str { self.bban_unchecked() } /// Get the bank identifier of the IBAN. The bank identifier might not be /// defined, in which case this method returns `None`. /// /// # Example /// ``` /// use iban::*; /// let iban: Iban = "AD12 0001 2030 2003 5910 0100".parse()?; /// assert_eq!(iban.bank_identifier(), Some("0001")); /// # Ok::<(), ParseIbanError>(()) /// ``` pub fn bank_identifier(&self) -> Option<&str> { match self.country_code() { "AD" => Some(0..4), "AE" => Some(0..3), "AL" => Some(0..3), "AT" => Some(0..5), "AZ" => Some(0..4), "BA" => Some(0..3), "BE" => Some(0..3), "BG" => Some(0..4), "BH" => Some(0..4), "BR" => Some(0..8), "BY" => Some(0..4), "CH" => Some(0..5), "CR" => Some(0..4), "CY" => Some(0..3), "CZ" => Some(0..4), "DE" => Some(0..8), "DK" => Some(0..4), "DO" => Some(0..3), "EE" => Some(0..2), "EG" => Some(0..3), "ES" => Some(0..4), "FI" => Some(0..3), "FO" => Some(0..4), "FR" => Some(0..5), "GB" => Some(0..4), "GE" => Some(0..2), "GI" => Some(0..4), "GL" => Some(0..4), "GR" => Some(0..3), "GT" => Some(0..4), "HR" => Some(0..7), "HU" => Some(0..3), "IE" => Some(0..4), "IL" => Some(0..3), "IQ" => Some(0..4), "IS" => Some(0..2), "IT" => Some(1..6), "JO" => Some(4..8), "KW" => Some(0..4), "KZ" => Some(0..3), "LB" => Some(0..4), "LC" => Some(0..4), "LI" => Some(0..5), "LT" => Some(0..5), "LU" => Some(0..3), "LV" => Some(0..4), "MC" => Some(0..5), "MD" => Some(0..2), "ME" => Some(0..3), "MK" => Some(0..3), "MR" => Some(0..5), "MT" => Some(0..4), "MU" => Some(0..6), "NL" => Some(0..4), "NO" => Some(0..4), "PK" => Some(0..4), "PL" => None, "PS" => Some(0..4), "PT" => Some(0..4), "QA" => Some(0..4), "RO" => Some(0..4), "RS" => Some(0..3), "SA" => Some(0..2), "SC" => Some(0..6), "SE" => Some(0..3), "SI" => Some(0..5), "SK" => Some(0..4), "SM" => Some(1..6), "ST" => Some(0..4), "SV" => Some(0..4), "TL" => Some(0..3), "TN" => Some(0..2), "TR" => Some(0..5), "UA" => Some(0..6), "VA" => Some(0..3), "VG" => Some(0..4), "XK" => Some(0..2), _ => panic!( "Unknown country! Please file an issue at \ https://github.com/ThomasdenH/iban_validate." ), } .map(|range| &self.electronic_str()[4..][range]) } /// Get the branch identifier of the IBAN. The branch identifier might not be /// defined, in which case this method returns `None`. /// /// # Example /// ``` /// use iban::*; /// let iban: Iban = "AD12 0001 2030 2003 5910 0100".parse()?; /// assert_eq!(iban.branch_identifier(), Some("2030")); /// # Ok::<(), ParseIbanError>(()) /// ``` pub fn branch_identifier(&self) -> Option<&str> { match self.country_code() { "AD" => Some(4..8), "AE" => None, "AL" => Some(3..7), "AT" | "AZ" => None, "BA" => Some(3..6), "BE" => None, "BG" => Some(4..8), "BH" => None, "BR" => Some(8..13), "BY" | "CH" | "CR" => None, "CY" => Some(3..8), "CZ" | "DE" | "DK" | "DO" | "EE" => None, "EG" => Some(3..6), "ES" => Some(4..8), "FI" | "FO" | "FR" => None, "GB" => Some(4..10), "GE" | "GI" | "GL" => None, "GR" => Some(4..7), "GT" | "HR" => None, "HU" => Some(3..7), "IE" => Some(4..10), "IL" => Some(3..6), "IQ" => Some(4..7), "IS" => Some(2..4), "IT" => Some(6..11), "JO" | "KW" | "KZ" | "LB" | "LC" | "LI" | "LT" | "LU" | "LV" => None, "MC" => Some(5..10), "MD" | "ME" | "MK" => None, "MR" => Some(5..10), "MT" => Some(4..9), "MU" => Some(6..8), "NL" | "NO" | "PK" => None, "PL" => Some(0..8), "PS" | "PT" | "QA" | "RO" | "RS" | "SA" => None, "SC" => Some(6..8), "SE" | "SI" | "SK" => None, "SM" => Some(6..11), "ST" => Some(4..8), "SV" | "TL" => None, "TN" => Some(2..5), "TR" | "UA" | "VA" | "VG" => None, "XK" => Some(2..4), _ => panic!( "Unknown country! Please file an issue at \ https://github.com/ThomasdenH/iban_validate." ), } .map(|range| &self.electronic_str()[4..][range]) } } impl From<Iban> for BaseIban { fn from(value: Iban) -> BaseIban { value.base_iban } } impl fmt::Debug for Iban { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&self.base_iban, f) } } impl fmt::Display for Iban { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.base_iban, f) } } /// Represents an IBAN. To obtain it, make use of the [`parse()`] function, which will make sure the /// string follows the ISO 13616 standard. Apart from its own methods, `Iban` implements [`IbanLike`], /// which provides more functionality. /// /// The impementation of [`Display`](std::fmt::Display) provides spaced formatting of the IBAN. Electronic /// formatting can be obtained via [`electronic_str`](IbanLike::electronic_str). /// /// A valid IBAN satisfies the defined format, has a valid checksum and has a BBAN format as defined in the /// IBAN registry. /// /// # Examples /// ```rust /// use iban::*; /// let address = "KZ86125KZT5004100100".parse::<iban::Iban>()?; /// assert_eq!(address.to_string(), "KZ86 125K ZT50 0410 0100"); /// # Ok::<(), iban::ParseIbanError>(()) /// ``` /// /// [`parse()`]: https://doc.rust-lang.org/std/primitive.str.html#method.parse #[derive(Clone, Copy, Eq, PartialEq, Hash)] pub struct Iban { /// The inner IBAN, which has been checked. base_iban: BaseIban, } /// An error indicating the IBAN could not be parsed. /// /// # Example /// ```rust /// use iban::{BaseIban, Iban, ParseIbanError, ParseBaseIbanError}; /// use std::convert::TryFrom; /// /// // The following IBAN has an invalid checksum /// assert_eq!( /// "MR00 0002 0001 0100 0012 3456 754".parse::<Iban>(), /// Err(ParseIbanError::from(ParseBaseIbanError::InvalidChecksum)) /// ); /// /// // The following IBAN doesn't follow the country format /// let base_iban: BaseIban = "AL84212110090000AB023569874".parse()?; /// assert_eq!( /// Iban::try_from(base_iban), /// Err(ParseIbanError::InvalidBban(base_iban)) /// ); /// # Ok::<(), ParseBaseIbanError>(()) /// ``` #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, Error)] pub enum ParseIbanError { /// This variant indicates that the basic IBAN structure was not followed. #[error("the string does not follow the base IBAN rules")] InvalidBaseIban { /// The error indicating what went wrong when parsing the Iban. #[from] source: ParseBaseIbanError, }, /// This variant indicates that the BBAN did not follow the correct format. /// The `BaseIban` provides functionality on the IBAN part of the /// address. #[error("the IBAN doesn't have a correct BBAN")] InvalidBban(BaseIban), /// This variant indicated that the country code of the IBAN was not recognized. /// The `BaseIban` provides functionality on the IBAN part of the /// address. #[error("the IBAN country code wasn't recognized")] UnknownCountry(BaseIban), } impl<'a> TryFrom<&'a str> for Iban { type Error = ParseIbanError; fn try_from(value: &'a str) -> Result<Self, Self::Error> { value .parse::<BaseIban>() .map_err(ParseIbanError::from) .and_then(Iban::try_from) } } impl TryFrom<BaseIban> for Iban { type Error = ParseIbanError; fn try_from(base_iban: BaseIban) -> Result<Iban, ParseIbanError> { let country_match = RE_COUNTRY_CODE .matches(base_iban.country_code()) .iter() .next(); if let Some(country_index) = country_match { let address_match = RE_ADDRESS_REMAINDER .matches(base_iban.bban_unchecked()) .iter() .find(|&address_index| address_index == country_index); if address_match.is_some() { Ok(Iban { base_iban }) } else { Err(ParseIbanError::InvalidBban(base_iban)) } } else { Err(ParseIbanError::UnknownCountry(base_iban)) } } } impl str::FromStr for Iban { type Err = ParseIbanError; fn from_str(address: &str) -> Result<Self, Self::Err> { Iban::try_from(address) } } #[cfg(feature = "serde")] impl Serialize for Iban { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { self.base_iban.serialize(serializer) } } #[cfg(feature = "serde")] impl<'de> Deserialize<'de> for Iban { fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { struct IbanStringVisitor; use serde::de; impl<'vi> de::Visitor<'vi> for IbanStringVisitor { type Value = Iban; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!(formatter, "an IBAN string") } fn visit_str<E: de::Error>(self, value: &str) -> Result<Iban, E> { value.parse::<Iban>().map_err(E::custom) } } deserializer.deserialize_str(IbanStringVisitor) } }