How to auto add slash(/) in expiry date field input javascript - javascript

I wanna auto add slash in credit card expiry date field input. I wanna add slash after type 2 character and remove slash after delete third digit. Example, 23/ (auto add slash after type number 3) 23/4 (auto remove slash after delete number 4)
addSlashes(elementID) {
let ele = document.getElementById(elementID)
const value = ele.value
let finalVal = null
if (value.length === 2) {
finalVal = `${value}/`
}
document.getElementById(elementID).value = finalVal
},

As soon as the / is added after 2 characters, the total length becomes 3. So, it is not very clear how the operation should happen.
However, if this is for some automatic changes to happen when progressive typing takes place, here is the code to add a / automatically when the user has typed 2 characters and remove it when the next character is added after the /
Edit
OP needs to delete the / when the 3rd digit is removed.
function modifyInput(ele) {
if (ele.value.length === 2)
ele.value = ele.value + '/'
else
if (ele.value.length === 3 && ele.value.charAt(2) === '/')
ele.value = ele.value.replace('/', '');
}
<input type="text" onkeyup="modifyInput(this)">

Related

How can I make regex detect backspace or delete button inside a onChange property in React

Hey I have an input field. using react at the moment the input field is for an expiry date for bank card
I am using regex to restrict the input field to only accept numbers and a dash -. Inserting the dash after the length of input text reaches 4 by doing this:
let expiryTime = e.target.value;
if (e.target.value.length === 4) {
expiryTime += "-";
}
But I have a problem when I try to delete the the characters i cant delete past 4th character because of the above statement
the output I was looking for was (YYYY-MM). here is my function using react for this:
const handleExpiryDate = (e) => {
// this regex is forcing the user to only have numbers or a dash
const reg = new RegExp(/^[\d-]*$/g)
if (!reg.test(e.target.value)) {
return;
}
// cant delete past 4 because of this condition I still want to auto input the dash once a user types 4 numbers for the YYYY then dash MM
let expiryTime = e.target.value;
if (e.target.value.length === 4) {
expiryTime += "-";
}
setExpiryDate(expiryTime);
}
How can I solve it? is there a regex i can use to detect backspace or delete was pushed, or how can incopurate such regex into my regex condition like the \b?
// here is the element
<input
className={styles.left_inputs}
type="text"
name="expiry_date"
placeholder="Expiration date (YYYY-MM)"
maxLength="7"
onChange={handleExpiryDate}
value={expiryDate}
/>

Formatting input value using javascript as the user types a value into the input field

I have an input field of length 14 into which the user types a value. As the user types into it, I would like a space to be added automatically after first 2 characters and then after next 3 characters and then after next 3 characters. so if the user wants to enter 12345678901, it should be formatted to 12 345 678 901.
Also when user uses backspace to clear the characters, the space should automatically be removed. So in the above case when the cursor reaches 9 and user hits backspace, the cursor should move two places to left clearing 9 and the space before it.
I tried following the credit card formatting here Format credit card number but couldn't understnd how it is done. The code from above link is
formatInput(event: any) {
var v = event.value.replace(/\s+/g, '').replace(/[^0-9]/gi, '')
var matches = v.match(/\d{4,16}/g);
var match = matches && matches[0] || ''
var parts = []
for (let i=0, len=match.length; i<len; i+=4) {
parts.push(match.substring(i, i+4))
}
if (parts.length) {
(<HTMLInputElement>document.getElementById("txtInput")).value =
parts.join(' ')
} else {
(<HTMLInputElement>document.getElementById("txtInput")).value
= event.value;
}
}
The above code generates spaces after every 4 digits. My requirement is to accept any characters and generate spaces after first 2 characters and then after next 3 characters and then after next 3 characters. Please help me out with this.
this is a working example that solves your problem.
function format(str) {
if (str.length < 2) return str
else {
let [fl,sl,...lstr] = str
lstr =lstr.reduce((acc, el, i) => (i % 3 ? acc[acc.length - 1]+=el : acc.push(el), acc),[])
return `${fl}${sl} ${lstr.join(' ')}`.trim()
}
}
const [input,result]= document.querySelectorAll('#input,#result')
input.oninput =()=>{
const i = input.value.replace(/\s/g, '');
input.value= format(i)
}
<input type=text id=input />
<p id="result"></p>

US zip code automatically add - for 9 digits

How can I automatically add a - after the 5 digits of a US zip code (using AngularJS) if more than 5 digits are typed into the field and save it as a 9 digit string (like 12345-6789) to validate it?
index.html
<div class="field">
Country: {{location.zipcode}}
</div>
index.controller.js
...
$scope.validateZipCode = function(location.zipcode) {
return (zipcode.length === 5 || (zipcode.length === 10 && zipcode[5] === '-'));
}
...
The user are not adding the - on their own and I feel like having an automatically populated - would be good UX.
Please don't recommend the use of any libraries or zipcode validation APIs. This is a legacy project that needs minimal additions.
There's not going to be an out of the box way of doing this, so you'll have to create a function to count the characters and insert your hyphen when needed.
here is a basic example of how you can go about it.
const input = document.getElementById('zip');
document.addEventListener('keyup', e => {
const val = e.target.value;
if (val.length < 6) { input.value = e.target.value; }
if (val.length > 5) {
// There are better ways to do this part, but here's the basic idea
input.value = input.value.replace('-', '');
input.value = input.value.substring(0, 5) + '-' + input.value.substring(5, input.value.length);
}
});
<input id="zip" />
One thing to note is that you can use an out of the box way to validate your input requirements by using the pattern attribute

Adding a 0 before digit in an input

I need help when you enter a single digit month in a date of birth that will automatically add a 0 digit in a single digit in an input.Here's my code:
$('#dob_dd').blur(function(){
var addzero = $('#dob_dd').val().length;
if (addzero.length != 2) {
addzero = '0' + addzero;
} else {
return addzero;
}
});
If you want to update the displayed value. it's as simple as
$('#dob_dd').blur(function(){
var $this = $(this);
$this.value(('0' + $this.value()).substr(-2));
});
This will function correctly if the selector selects multiple targets as well
You already specify that you want to check the length of $('#dob_dd'). So maybe it should be :
if (addzero != 2)
Then of course you need to update the value using for instance $('#dob_dd').val("new value")

Verifying text-field entry and changing class for user feedback

In this jsfiddle example, I have created a text-entry field that responds to the characters entered and appends a class to the parent <div> element for visual feedback based on whether the entry is expected, partial, or has an error.
In this case, the text field is for serial number entry; the field contents will eventually be sent to a dynamic table for building out an order. Because of this, the serial number must have an absolute value in the prefix (i.e: ABCDE in the example) and contain exactly 14 characters... I'm having difficulty coming up with a working code that will turn the text box green if the prefix is correct and remain green regardless of the remaining 9 characters (although they do need to be strictly numeric and end in a letter).
Additionally, I have a feeling there is a shorter and more elegant way to implement the script for the prefix check. Currently, I'm using:
if (el.value == "abcde" || el.value == "ABCDE") {
document.getElementById('serial').className = 'serial-entry success';
} else if (el.value == "a" || el.value == "ab" || el.value == "abc" || el.value == "abcd" || el.value == "A" || el.value == "AB" || el.value == "ABC" || el.value == "ABCD") {
document.getElementById('serial').className = 'serial-entry warning';
... where I know there's got to be a better way to write the expected ascending prefix values other than (el.value == "a" || el.value == "ab" ||... and so on. Using my current method, I would need to write half-a-billion variants of the el.value in order to satisfy all combinations.
Please be aware that I am not versed in JS; everything I know I've picked up from this site. It's the equivalent of moving to a foreign country and learning the language solely by eavesdropping on conversation - my grammar, syntax, and vocabulary are sparse, at best. In other words: feel free to humiliate me with sage-like wisdom.
--- EDIT: Answered! ---
Thanks to Felix Kling for the solution. I should have been more clear on where the state changes would occur, so I'll do so now and then include the code.
Rules:
1.) As the user enters the first letters of the prefix in correct order ("abcde"), the class of the text box should change to let the user know that they're on the right track, but not quite finished (partial).
2.) If the prefix is entered exact and we're agnostic of the following numbers ("123456789"), but they eventually do enter the correct prefix and a total of 14 characters, then the state (class) of the text box should toggle showing a success indicator.
3.) All other entries into the text box should be considered as erroneous, and an error class should be appended respectively.
4.) Lastly, if the user clears the text box of any string they entered, then the box should revert its class to the original state and not persist with any of the above classes.
Here is Felix's revised jfiddle.
And purely the JS:
function checkSerial(el) {
var value = el.value.toLowerCase();
var prefix = 'abcde';
var className = 'error'; // assume no match
if (!value) {
className = '';
}
else if (value.length === 14 &&
value.indexOf(prefix) === 0) { // match
className = 'success';
}
else if ((value.length >= prefix.length &&
value.indexOf(prefix) === 0) || // match
prefix.indexOf(value) === 0) { // partial match
className = 'warning';
}
document.getElementById('serial').className = 'serial-entry ' + className;
}
You could just use .indexOf and test that the string starts with the prefix:
document.getElementById('serial').className =
el.value.toLowerCase().indexOf('abcde') === 0 ?
'serial-entry success' :
'serial-entry warning';
For the three case, match, partial match, no match, you can check whether the input string is shorter than the prefix and apply the same logic, but vice versa:
var value = el.value.toLowerCase();
var prefix = 'abcde';
var className = 'error'; // assume no match
if (value.length >= prefix.length) {
if (value.indexOf(prefix) === 0) { // match
className = 'success';
}
}
else if (prefix.indexOf(value) === 0) { // partial match
className = 'warning'
}
document.getElementById('serial').className = 'serial-entry ' + className;
DEMO
suggesting to use RegEx to match the prefix as follows:
var val = el.value;
if(val.match(/\bABCDE/g)!=null) {
document.getElementById('serial').className = "serial-entry success";
} else {
document.getElementById('serial').className = "serial-entry error";
}
this way you can easily validate if the input is starting exactly with 'ABCDE'.
You can change the RegEx to suite your requirements.
Try this:
if(el.value.toLowerCase().indexOf('abcde') == 0 && el.value.length == 14)
document.getElementById('serial').className = "serial-entry success";
else
document.getElementById('serial').className = "serial-entry warning";

Categories