number_input.tsx 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. }
  8. const NumberInput: React.FC<NumberInputProps> = ({ placeholder, extendedStyle, onChangeText }) => {
  9. const [inputValue, setInputValue] = useState<string>("");
  10. const [error, setError] = useState("");
  11. //if users input non-number, show error message
  12. const validateInput = (input: string) => {
  13. const regex = /^[0-9\b]+$/;
  14. if (!input.trim()) {
  15. setError("");
  16. setInputValue(input);
  17. onChangeText(input);
  18. return;
  19. }
  20. if (regex.test(input)) {
  21. setInputValue(input);
  22. setError("");
  23. onChangeText(input);
  24. } else {
  25. setError("Please enter only numbers");
  26. }
  27. };
  28. return (
  29. <View>
  30. <View style={[styles.inputContainer, extendedStyle]}>
  31. <TextInput
  32. keyboardType="numeric"
  33. placeholder={placeholder}
  34. style={[styles.input]}
  35. onChangeText={(text) => validateInput(text)}
  36. value={inputValue}
  37. />
  38. </View>
  39. {error && <Text style={styles.errorMessage}>{error}</Text>}
  40. </View>
  41. );
  42. };
  43. const styles = StyleSheet.create({
  44. inputContainer: {
  45. width: "100%",
  46. maxWidth: "100%",
  47. flexDirection: "row",
  48. alignItems: "center",
  49. justifyContent: "center",
  50. borderWidth: 1,
  51. borderColor: "#bbbbbb",
  52. borderRadius: 10,
  53. padding: 15,
  54. margin: 10,
  55. },
  56. input: {
  57. flex: 1,
  58. marginLeft: 5,
  59. },
  60. errorMessage: {
  61. fontSize: 12,
  62. color: "#ff0033",
  63. marginLeft: 20,
  64. },
  65. });
  66. export default NumberInput;