Search code examples
reactjsreact-nativetextinput

Texinput without whitespace?


I need to alert when user enters white space while filling the textınput field. By the time doing this I do not want keyboard to disappear. I have no clue how to do this any idea?


Solution

  • You can use regex for this.

    import React, { Component } from "react";
    import {  View, TextInput } from "react-native";
    
    
    class App extends Component {
    
      state = {
         text : ''
      }
    
      hasWhiteSpace(s) {
        let regSpace= new RegExp(/\s/);
        // Check for white space
        if (regSpace.test(s)) {
          //your logic
          alert("Please Check Your Fields For Spaces");
          return false;
        } else {
           this.setState({ text:s })
        }
        return true;
      }
    
      render() {
        return (
          <View>
             <TextInput
                style={{ height: 40, borderColor: "gray", borderWidth: 1 }}
                onChangeText={text => {
                this.hasWhiteSpace(text);
              }}
              value={this.state.text}
            />
          </View>
        );
      }
    }
    
    export default App;
    

    working example

    https://codesandbox.io/embed/04jl3800vw