Skip to content

Instantly share code, notes, and snippets.

@miguelgisbert
Created September 26, 2023 13:20
Show Gist options
  • Save miguelgisbert/d62e04d745ad5fcc3c94767b667e90d4 to your computer and use it in GitHub Desktop.
Save miguelgisbert/d62e04d745ad5fcc3c94767b667e90d4 to your computer and use it in GitHub Desktop.
IBAN validation (React MUI 5)
import React, { useState, useEffect } from 'react';
import TextField from '@mui/material/TextField';
import InputAdornment from '@mui/material/InputAdornment';
import HelpOutlineIcon from '@mui/icons-material/HelpOutline';
import Tooltip from '@mui/material/Tooltip';
export default function IbanInput() {
const [iban, setIban] = useState('');
const [ibanError, setIbanError] = useState(false);
useEffect(() => {
const ibanRE = /([a-zA-Z]{2})[\s\t-]*\d{2}[\s\t-]*(\d{2}[\s\t-]*){10}/;
setIbanError(!ibanRE.test(iban));
}, [iban]);
const handleChange = (event) => {
let value = event.target.value;
// Only letters at 2 first positions and only numbers at the other ones
value = value.slice(0,2).replace(/[^a-zA-Z]/g, '') + value.slice(2).replace(/[^\d]/g, '');
// Auto separation with '-'
if(value.length > 4 && value.length < 25) {
value = value.replace(/(.{4})(?=\d)/g, '$1-');
}
setIban(value);
}
return (
<TextField
value={iban}
onChange={handleChange}
error={ibanError}
helperText={ibanError ? 'IBAN not valid' : ''}
inputProps={
{maxLength: 29} // 6 x 4 for IBAN number + 5 separation char '-'
}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<Tooltip title="Enter the IBAN number including the corresponding country code so we can pay the monthly payslip..">
<HelpOutlineIcon />
</Tooltip>
</InputAdornment>
)
}}
/>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment