2

i want to only allow text input no copy pasting in text

i've already made it that the numeric keyboard should open but i want to only allow numbers in this input field period

<TextInput
         underlineColorAndroid='transparent'
         style={styles.TextInputStyle}
         placeholder='0.00'
         keyboardType={'numeric'}
         value={this.state.shippingCharge}
         onChangeText={(shippingCharge) => this.setState({ shippingCharge })}
     />
prog
  • 173
  • 1
  • 3
  • 12

1 Answers1

2

Try to use Regex validation on input (numeric with maximum length 100 numbers for example):

<TextInput
     underlineColorAndroid='transparent'
     style={styles.TextInputStyle}
     placeholder='0.00'
     keyboardType={'numeric'}
     value={this.state.shippingCharge}
     onChangeText={this.onChangeTextInput}
 />



onChangeTextInput = (text) => {
    const numericRegex = /^([0-9]{1,100})+$/
    if(numericRegex.test(text)) {
        this.setState({ shippingCharge: text })
    }
}
Idan
  • 3,604
  • 1
  • 28
  • 33
  • but i already have an action being done with on change text can i have 2 onchangetext's in one textInput field – prog Aug 05 '19 at 21:10
  • @prog you tried my code? it's doing what you said – Idan Aug 05 '19 at 21:14
  • You can't have two onChangeText function, but you can merge their code. Other way is to split in validation and action, then call it both on other function. – Bruno Mazzardo Aug 05 '19 at 21:17
  • onChangeTextInput = (text) => { const numericRegex = /^([0-9]{1,100})+$/ if(numericRegex.test(text)) { this.setState({ shippingCharge: text } } } – prog Aug 05 '19 at 21:17
  • where should i place that chunk of code – prog Aug 05 '19 at 21:18
  • @BrunoMazzardo how do i merge the code – prog Aug 05 '19 at 21:19
  • @prog you can do that like my code, you take the merge code to outside function (but inside the class) and when the input will change the function are calling – Idan Aug 05 '19 at 21:27
  • @prog if you don't wanna separate the code to more function you can do this: `onChangeText={(shippingCharge)=> { (/^([0-9]{1,100})+$/).test(shippingCharge) ? this.setState({ shippingCharge }) : null } }` – Idan Aug 05 '19 at 21:31
  • There's typo, missing `)` after `this.setState({ shippingCharge: text }`. – Diamond Aug 05 '19 at 21:37
  • @Antonio my bad, i will fix it – Idan Aug 05 '19 at 21:41
  • @prog it helps? – Idan Aug 05 '19 at 21:55
  • it helped with that textinput but how should i apply it to my other text inputs and also its causing some problems with my app – prog Aug 05 '19 at 22:04
  • i think the main problem is it does not let me change delete the entered number because i guess thats consider whitespace so it just dosent let be hit backspace on that text input – prog Aug 05 '19 at 22:06
  • @prog You can attach all class code? and what exactly not working ? – Idan Aug 06 '19 at 08:44