Actualmente estoy buscando una manera de verificar el formato de un número.
Quiero aceptar solo decimales convencionales como: { 1 ; 1.1 ; 1.01 ; 15 ; 15.15}.
Actualmente, en mi cuadro de texto, puedo pasar números como, por ejemplo: 102.129.392.12 (como una dirección IP), etc.
Había pensado en poner una expresión regular para comprobar que el formato es bueno:
. .match(/^\d+(\.\d{1,2})?$/)pero no sé cómo implementarlo en un archivo .tsx
Soy nuevo en la tecnología de react.
Aquí está mi código.
const SupplyEvent = () => { const handleChangeQuantity = (value: string) => { if (chosenSupply) { setChosenSupply({ ...chosenSupply, quantity: value.replace(/,/g, '.'), // .match(/^\d+(\.\d{1,2})?$/) }); } }; return( <View style={styles.halfWidth}> <Input value={chosenSupply?.quantity} keyboardType="decimal-pad" onChangeText={handleChangeQuantity} disabled={mode === FormMode.read} /> </View> ); };Quiero agregar un mensaje en rojo para el usuario como 'Este número no es aceptado'
Tienen alguna idea ?
Gracias
... import React, { useState } from 'react'; import { Text, StyleSheet } from 'react-native'; const SupplyEvent = () => { const [error, setError] = useState(null); const handleChangeQuantity = (value: string) => { const resolveValue = value.replace(/,/g, '.'); if(!resolveValue.match(/^\d+(\.\d{1,2})?$/)){ setError("Format isn't correct"); } else if (chosenSupply) { setChosenSupply((prevChosenSupply)=>({ ...prevChosenSupply, quantity: resolveValue })); } }; return( <View style={styles.halfWidth}> {error && <Text style={styles.errorMessage}>{error}</Text>} <Input value={chosenSupply?.quantity} keyboardType="decimal-pad" onChangeText={handleChangeQuantity} disabled={mode === FormMode.read} /> </View> ); }; const styles = StyleSheet.create({ ... errorMessage: { color: 'white', backgroundColor: 'red', borderRadius: 5 } });