Hay un componente de tarjeta de crédito. Le pide al usuario que ingrese la información de la tarjeta de crédito. Sin embargo, quiero colocar automáticamente una barra entre el día y el mes cuando el usuario ingresa la fecha de vencimiento de la tarjeta de crédito. Busqué la entrada de la fecha de vencimiento como "barra automática cuando se ingresan 2 dígitos", pero aún no he tenido éxito.
puedo escribir; 0614
El formato que quiero; 14/06
¿Cómo puedo resolverlo?
js
const [expDateValidationState, setExpDateValidationState] = useState({ error: false, helperText: '', }); const expDateOnChange = (event) => { if (expDateValidator(event.target.value)) { setExpDateValidationState({ error: false, helperText: '' }); setPaymentInfo({ ...paymentInfo, expDate: event.target.value === '' ? null : event.target.value, }); } else { setExpDateValidationState({ error: true, helperText: 'Please enter your expire date.', }); setPaymentInfo({ ...paymentInfo, expDate: null, }); } const handleExpDateChange = (event) => { expDateOnChange(event); handleInputChange(event); };validador
export const expDateValidator = (expDate) => { const expDateRegex = /^(0[1-9]|1[0-2])\/?([0-9]{4}|[0-9]{2})$/; return expDateRegex.test(expDate); };html
<AS.TextField placeholder="aa/YY" inputProps={{ maxLength: 5 }} onChange={handleExpDateChange} error={expDateValidationState.error} helperText={expDateValidationState.helperText} name="expDate" value={paymentInfo.expDate} />prueba este
const expDateOnChange = (event) => { if (expDateValidator(event.target.value)) { setExpDateValidationState({ error: false, helperText: '' }); let value = event.target.value; if (value.length===2) value += "/" setPaymentInfo({ ...paymentInfo, expDate: event.target.value === '' ? null : value, }); } else { setExpDateValidationState({ error: true, helperText: 'Please enter your expire date.', }); setPaymentInfo({ ...paymentInfo, expDate: null, }); }Cuando cambio algún dato suelo ponerlo en el estado. Si también mantiene sus datos en el estado, puede modificar su handleExpDateChange a algo como esto:
const [expirationDate, setExpirationDate] = useState(); const handleExpDateChange = (event) => { if (event.target?.value?.length === 2 && expirationDate.length < 3) { setExpirationDate(event.target.value + '/') } else { setExpirationDate(event.target.value) } }Esto se puede simplificar si usas una expresión ternaria o de cualquier otra forma, pero esto es muy simple y lo primero que se me ocurrió. Esperamos que esto sea útil.