Home > OS >  How can I set minimum value and Max value to TextInput
How can I set minimum value and Max value to TextInput

Time:04-10

As an example I want to give minimum value as 5000 and maximum value as 200000,In between those value user can type, if not in between user can't type.

CodePudding user response:

Here is a full example (https://snack.expo.dev/zlwWokoFK).

The way to do this is to to not let the text update if the length of the text is below or above the limits. In the onChangeText function.

Heres the code below

import * as React from 'react';
import { Text, View, TextInput } from 'react-native';


export default function App() {

  /* 
    Specify your upper and lower limits of length
  */
  const LOWER_LIMIT = 10;
  const HIGHER_LIMIT = 20;

  /* 
    State for the text
  */
  const [text, setText] = React.useState("ab".repeat(LOWER_LIMIT/2));

  /* 
    Function to update the text 
  */
  const onChangeText = (newText)=>{
    /* 
      If text is above or below length of limits then exit function
    */
    if (newText.length < LOWER_LIMIT || newText.length>HIGHER_LIMIT){
      return;
    }
    // Else update text
    setText(newText);
  }


  return (
    <View style={{
      flex:1,
      justifyContent:"center",
      }}>
        <TextInput
         onChangeText={value=>onChangeText(value)}
         multiline
         value={text}
         style={{
          height: 400,
          margin: 12,
          borderWidth: 1,
          padding: 10,
        }}
        />
    </View>
  );
}


CodePudding user response:

You can use editable = {false} in TextInput . For Example :

<View pointerEvents="none">
<TextInput value="I am read only" editable={false} />
</View>

So here make useState for editable boolean value and set, unset as per your condition's.

  • Related