Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  36] [ 3]  / answers: 1 / hits: 79870  / 11 Years ago, sun, june 23, 2013, 12:00:00

I'm really new in JavaScript and I would like to add to my input text, space insertion for IBAN account registering.





<input type=text name=iban onkeyup=if(this.value.length > 34){this.value=this.value.substr(0, 34);} />





There is my input field; could someone tell me how I can do this?


More From » regex

 Answers
5

The existing answers are relatively long, and they look like over-kill. Plus they don't work completely (for instance, one issue is that you can't edit previous characters).



For those interested, according to Wikipedia:




Permitted IBAN characters are the digits 0 to 9 and the 26 upper-case Latin alphabetic characters A to Z.




Here is a relatively short version that is similar to the existing answers:





document.getElementById('iban').addEventListener('input', function (e) {
e.target.value = e.target.value.replace(/[^dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
});

<label for=iban>iban</label>
<input id=iban type=text name=iban />








As stated above, the caveat is that you can't go back and edit previous characters. If you want to fix this, you would need to retrieve the caret's current position by initially accessing the selectionEnd property and then setting the caret's position after the regex formatting has been applied.





document.getElementById('iban').addEventListener('input', function (e) {
var target = e.target, position = target.selectionEnd, length = target.value.length;

target.value = target.value.replace(/[^dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim();
target.selectionEnd = position += ((target.value.charAt(position - 1) === ' ' && target.value.charAt(length - 1) === ' ' && length !== target.value.length) ? 1 : 0);
});

<label for=iban>iban</label>
<input id=iban type=text name=iban />





You will notice that there is a slight issue when the character after the caret is a space (because the space wasn't accounted for when initially retrieving the caret's position to begin with). To fix this, the position is manually incremented if the succeeding character is a space (assuming a space was actually added - which is determined by comparing the length before and after replacing the characters).


[#77464] Friday, June 21, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
braeden

Total Points: 231
Total Questions: 96
Total Answers: 86

Location: Somalia
Member since Mon, Dec 28, 2020
3 Years ago
braeden questions
Fri, Oct 29, 21, 00:00, 3 Years ago
Thu, Oct 10, 19, 00:00, 5 Years ago
;