number_input.tsx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import React, { useState } from "react";
  2. import { View, Text, TextInput, StyleSheet, ViewStyle, StyleProp } from "react-native";
  3. interface NumberInputProps {
  4. placeholder: string;
  5. extendedStyle?: StyleProp<ViewStyle>;
  6. onChangeText: (text: string) => void;
  7. editable?: boolean;
  8. }
  9. const NumberInput: React.FC<NumberInputProps> = ({ placeholder, extendedStyle, onChangeText, editable }) => {
  10. const [inputValue, setInputValue] = useState<string>("");
  11. const [error, setError] = useState("");
  12. //if users input non-number, show error message
  13. const validateInput = (input: string) => {
  14. const regex = /^[0-9\b]+$/;
  15. if (!input.trim()) {
  16. setError("");
  17. setInputValue(input);
  18. onChangeText(input);
  19. return;
  20. }
  21. if (regex.test(input)) {
  22. setInputValue(input);
  23. setError("");
  24. onChangeText(input);
  25. } else {
  26. setError("Please enter only numbers");
  27. }
  28. };
  29. return (
  30. <View style={[styles.mainContainer, extendedStyle]}>
  31. <View style={styles.inputContainer}>
  32. <TextInput
  33. keyboardType="numeric"
  34. placeholder={placeholder}
  35. placeholderTextColor={"#888888"}
  36. style={[styles.input, , {fontFamily: 'Roboto-Regular'}]}
  37. onChangeText={(text) => validateInput(text)}
  38. value={inputValue}
  39. editable={editable}
  40. />
  41. </View>
  42. {error && <Text style={styles.errorMessage}>{error}</Text>}
  43. </View>
  44. );
  45. };
  46. const styles = StyleSheet.create({
  47. mainContainer: {
  48. width: "100%",
  49. maxWidth: "100%",
  50. height: "100%",
  51. maxHeight: "100%",
  52. },
  53. inputContainer: {
  54. flexDirection: "row",
  55. alignItems: "center",
  56. justifyContent: "center",
  57. borderWidth: 1,
  58. borderColor: "#bbbbbb",
  59. borderRadius: 12,
  60. padding: 20,
  61. },
  62. input: {
  63. flex: 1,
  64. marginLeft: 5,
  65. fontSize: 16,
  66. },
  67. errorMessage: {
  68. fontSize: 14,
  69. color: "#ff0033",
  70. fontWeight: "400",
  71. marginLeft: 10,
  72. marginTop: 10,
  73. },
  74. });
  75. export default NumberInput;