0

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);
    })
};

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You can also use input.trim() to remove trailing and leading whitespace from a string.
1

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.