Search code examples
javascripttypescriptreact-nativereact-hook-formreact-native-ui-kitten

How do I prevent a user from inputting multiple periods in React Native?


I'm using UI Kitten's Input component and react-hook-form and I don't want the user to put more than one period onPress so once one period is inputted, the user wouldn't be allowed to input another; this is for decimal points.

Example:

Allowed Input -> .9, 0.9
Disallowed Input -> ..9, ..09

Any help would be appreciated, thank you!


Solution

  • To monitor changes to the input and check it before changing the state, you may use the onChangeText prop of the UI Kitten's Input component. If the input string only has one period, you may use a regular expression to determine whether it is legitimate and update the state accordingly. If it is invalid, you can produce an error message. You can get idea from this code:

    const MyInput = () => {
    const [value, setValue] = useState('');
    
    const handleChange = (text) => {
    const pattern = /^\d*(\.\d{0,2})?$/;
    if (!pattern.test(text)) {
      return;
    }
    setValue(text);
    };
    
    return (
    <Input
      value={value}
      onChangeText={handleChange}
      placeholder="Enter decimal value"
    />
    );
    };
    
    export default MyInput;
    

    Only integers and a single period with a maximum of two decimal places are permitted in this code's input text validation. The status will not be updated if the input is invalid.