Home > OS >  Input Validation and spaces
Input Validation and spaces

Time:09-17

I have the Input below using React Native.

<View style={ styles.container }>
        <Input 
        placeholder="Add new chat"
        value={input}
        onChangeText={(text) => setInput(text)}
        leftIcon={
            <Icon name="wechat" type="antdesign" size={24} color="black" />
        }
        />

        <Pressable style={styles.buttonAdd} onPress={createChat}>
            <Text style={styles.text}>Create</Text>
        </Pressable>

    </View>

If i type nothing then i get my alert which is fine however if i put 1 or spaces the data gets submited. How can i disallow the submit and so set the alert when there is only spaces?

    const [input, setInput] = useState("");

const createChat = async () => {
    if(!input) {
        alert("The chat name cannot be blank");
        return;
    }
    await db
    .collection("chats")
    .add({
        chatName: input
    })
    .then(() => {
        navigation.goBack();
    })
    .catch(() => {
        alert(error);
    })
};

CodePudding user response:

You could just remove all spaces and check if the string is still longer than zero characters.

e.g.:

const submit = () => {
    if (input.replaceAll(' ', '').length > 0){
        // your submit logic here
    }
}

otherwise you could also test for regex, but this might be overkill for your needs.

CodePudding user response:

As input is a string, you can trim your string to remove any whitespaces from either end of the string.

Notice trim() will remove whitespaces from either end of the string, not the spaces in between words.

const string = "   A string with spaces at end  ";
console.log(string.trim());

const string_with_only_space = "      ";
console.log(string_with_only_space.trim());

if(!string_with_only_space.trim()) {
  console.log("STRING IS EMPTY");
} else {
  console.log("STRING IS NOT EMPTY");
}

You can change your if condition to

if(!input.trim()) {
  alert("The chat name cannot be blank");
  return;
}
  • Related