diff --git a/src/console.c b/src/console.c
index e77c400b3fa98552f0c405b8c3acc96ed65c92cc..fcac0e6de99669b1c407e33ee6575ac4ec3cd088 100644
--- a/src/console.c
+++ b/src/console.c
@@ -202,7 +202,7 @@ static void CONS_Bind_f(void)
 	}
 
 	key = G_KeyStringtoNum(COM_Argv(1));
-	if (!key)
+	if (key <= 0 || key >= NUMINPUTS)
 	{
 		CONS_Alert(CONS_NOTICE, M_GetText("Invalid key name\n"));
 		return;
diff --git a/src/g_input.c b/src/g_input.c
index f12ddb7114c4b935e79877de7195ee248c47f6c2..79e6fb94b93629be6e8527d0e646de1267cf11f4 100644
--- a/src/g_input.c
+++ b/src/g_input.c
@@ -1042,13 +1042,13 @@ INT32 G_KeyStringtoNum(const char *keystr)
 	if (!keystr[1] && keystr[0] > ' ' && keystr[0] <= 'z')
 		return keystr[0];
 
+	if (!strncmp(keystr, "KEY", 3) && keystr[3] >= '0' && keystr[3] <= '9')
+		return atoi(&keystr[3]);
+
 	for (j = 0; j < NUMKEYNAMES; j++)
 		if (!stricmp(keynames[j].name, keystr))
 			return keynames[j].keynum;
 
-	if (strlen(keystr) > 3)
-		return atoi(&keystr[3]);
-
 	return 0;
 }