I have created a RegExp schema to accepted text, numbers but no specials characters:
//Regex.jsx
const searchRegex = new RegExp("^[0-9a-zA-ZÀ-ÿ-',.\s]+$");
export default searchRegex
I call this schema in the component and check if the address matches the schema, to search only if the text matches the schema.
//SearchBar.jsx
import searchRegex from './Regex'
import searchLocation from './SearchLocation'
const SearchBar = () => {
const [address, setAddress] = useState('')
const [searchErr, setSearchErr] = useState(false)
const validate = () => {
if (searchRegex.test(address)) {
setSearchErr(true);
} setSearchErr(false);
};
return (
<input
name="text"
type="search"
placeholder="Address..."
autoComplete="none"
value={address}
onChange={(event) => {
setAddress(event.target.value)
}}
onKeyPress={(event) => {
if (event.key === 'Enter') {
validate()
} if (searchErr) {
searchLocation()
}
}}
/>
)
}
export default SearchBar
Since you don't have an else
or a return
in:
if (searchRegex.test(address)) {
setSearchErr(true);
} setSearchErr(false);
the setSearchErr(false);
is always called.
No issue in your regex.
Just add return
in if
condition. So it does not execute the below code if the condition meets true.
const validate = () => {
if (searchRegex.test(address)) {
return setSearchErr(true);
}
setSearchErr(false);
};
So there's a few typos in your example but other already answered that But the issue is your regex: ^[0-9a-zA-ZÀ-ÿ-',.\s]+$
The period ( . ) in Regex is interpreted as "Any character" so you also have to escape it with a backslash ( \ )
Here's is your fixed Regex: ^[0-9a-zA-ZÀ-ÿ-',\.\s]+$
I suggest you to check out Regex 101
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.