Skip to content

Commit c4789da

Browse files
Merge pull request #70 from haleema-khatun/main
Add ChatInput validation
2 parents b4cedf9 + ec44695 commit c4789da

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import React, { useState } from "react";
2+
3+
const ChatInput = ({ onSubmit }) => {
4+
const [input, setInput] = useState("");
5+
const [error, setError] = useState(null);
6+
7+
// Regex: allow a-z, A-Z, 0-9, spaces, and basic punctuation .,?!'":;()-
8+
const validInputRegex = /^[a-zA-Z0-9\s.,?!'":;()-]*$/;
9+
10+
const handleChange = (e) => {
11+
setInput(e.target.value);
12+
if (error) setError(null); // Clear error on edit
13+
};
14+
15+
const handleSubmit = (e) => {
16+
e.preventDefault();
17+
18+
const trimmedInput = input.trim();
19+
20+
if (trimmedInput.length === 0) {
21+
setError("Input cannot be empty or whitespace only.");
22+
return;
23+
}
24+
if (!validInputRegex.test(trimmedInput)) {
25+
setError("Input contains invalid characters. Only letters, numbers, and basic punctuation are allowed.");
26+
return;
27+
}
28+
29+
setError(null);
30+
onSubmit(trimmedInput);
31+
setInput(""); // Clear input field after successful submit
32+
};
33+
34+
return (
35+
<form onSubmit={handleSubmit} className="flex flex-col space-y-2 w-full max-w-md mx-auto p-4">
36+
<input
37+
type="text"
38+
value={input}
39+
onChange={handleChange}
40+
placeholder="Enter your health question..."
41+
className={`border p-3 rounded ${error ? "border-red-600" : "border-gray-300"} focus:outline-none focus:ring-2 focus:ring-blue-500`}
42+
aria-label="Health query input"
43+
/>
44+
{error && <p className="text-red-600 text-sm">{error}</p>}
45+
<button
46+
type="submit"
47+
className="bg-blue-600 text-white py-2 rounded hover:bg-blue-700 disabled:opacity-50"
48+
disabled={input.trim().length === 0}
49+
>
50+
Submit
51+
</button>
52+
</form>
53+
);
54+
};
55+
56+
export default ChatInput;

0 commit comments

Comments
 (0)