만들면서 배우는 react : 기초 - 10
입력되는 값을 유효성 검사를 통해서 원하는 것만 받으려고 한다!
먼저 영어가 입력이 되면, 무조건 다 대문자로 변환해서 노출할 것이다.
그러면 글자가 입력이 될 때마다 실시간으로 변환을 해야한다.
const Form = ({ handleFormSubmit }) => {
const [value, setValue] = React.useState("");
function handleInputChange(e) {
setValue(e.target.value.toUpperCase()); //대문자로 변환함
}
return (
<form onSubmit={handleFormSubmit}>
<input
type="text"
name="name"
placeholder="영어 대사를 입력해주세요"
value={value}
onChange={handleInputChange} //input에 변화가 생길때마다 실행
/>
<button type="submit">생성</button>
</form>
);
};
onChange 함수를 통해서, 글자가 입력이 될때마다 동작이 작동하도록 했다.
toUpperCase() 함수는 무조건 글자들을 대문자로 바꿔준다.
대문자로 바꿔서 setValue에 지정을 해준 뒤 value를 다시 input에 넣어주면 된다.
그 다음에는 한글이 입력되면 에러메시지를 노출할 거다.
이것도 마찬가지로, 글자가 입력될 때마다 유효성 검사를 하면 된다.
const Form = ({handleFormSubmit}) => {
const includesHangul = (text) => /[ㄱ-ㅎ|ㅏ-ㅣ|가-힣]/i.test(text); //유효성 검사!
const [value, setValue] = React.useState("");
const [errorMessage, setErrorMessage] = React.useState("");
function handleInputChange(e) {
const userValue = e.target.value;
setErrorMessage(""); //에러메시지 초기화
if (includesHangul(userValue)) { //한글이 입력되면 에러메시지 노출
setErrorMessage("한글은 입력할 수 없습니다.");
}
setValue(userValue.toUpperCase());
}
return (
<form onSubmit={handleFormSubmit}>
<input
type="text"
name="name"
placeholder="영어 대사를 입력해주세요"
value={value}
onChange={handleInputChange}
/>
<button type="submit">생성</button>
<p style=>{errorMessage}</p>
</form>
);
};
test() 메서드는 주어진 문자열이 정규 표현식을 만족하는지 판별하고, 그 여부를 true 또는 false로 반환한다.
\i 는 대소문자를 구별하지 않는 뜻이라고 한다. 잘 몰라서 검색해봤다 ㅎㅎ
한글이 입력될 때마다, 에러메시지를 set해주고 노출하면 되는데
실시간으로 체크하는 거기 때문에 한글이 입력되지 않았다면 에러메시지가 노출되면 안되므로 초기화해준다.
이제 마지막으로 빈값이 입력됐을 때도 에러메시지를 노출해주려고 한다.
방법은 동일하다~!!!!!
const Form = ({ updateMainCat }) => {
const includesHangul = (text) => /[ㄱ-ㅎ|ㅏ-ㅣ|가-힣]/i.test(text);
const [value, setValue] = React.useState("");
const [errorMessage, setErrorMessage] = React.useState("");
function handleInputChange(e) {
const userValue = e.target.value;
setErrorMessage("");
if (includesHangul(userValue)) {
setErrorMessage("한글은 입력할 수 없습니다.");
}
setValue(userValue.toUpperCase());
}
function handleFormSubmit(e) { //handleFormSubmit를 함수로 고쳤당
e.preventDefault();
setErrorMessage("");
if (value === "") { //입력된 값이 빈값일때 에러메시지 노출 & updateMainCat 미실행
setErrorMessage("빈 값으로 만들 수 없습니다.");
return;
}
updateMainCat(); //입력된 값이 정상일때 updateMainCat 실행.
}
return (
<form onSubmit={handleFormSubmit}>
<input
type="text"
name="name"
placeholder="영어 대사를 입력해주세요"
value={value}
onChange={handleInputChange}
/>
<button type="submit">생성</button>
<p style=>{errorMessage}</p>
</form>
);
};
const App = () => {
const CAT1 =
"https://cataas.com/cat/60b73094e04e18001194a309/says/react";
const CAT2 =
"https://cataas.com//cat/5e9970351b7a400011744233/says/inflearn";
const CAT3 =
"https://cataas.com/cat/595f280b557291a9750ebf65/says/JavaScript";
const [counter, setCounter] = React.useState(1);
const [mainCat, setMainCat] = React.useState(CAT1);
const [favorites, setFavorites] = React.useState([CAT1, CAT2]);
function updateMainCat() { // 이미지를 변경해준다
setCounter(counter + 1);
setMainCat(CAT2);
}
function handleHeartClick() {
setFavorites([...favorites, CAT3]);
}
return (
<div>
<Title>{counter}번째 고양이 가라사대</Title>
<Form updateMainCat={updateMainCat} />
<MainCard img={mainCat} onHeartClick={handleHeartClick} />
<Favorites favorites={favorites} />
</div>
);
};
입력된 값이 정상일 때는 이미지가 바뀌어야 하고,
잘못된 값이 입력됐을 때는 이미지가 바뀌면 안되기 때문에
입력된 값에 따라 updateMainCat을 설정해줬다.
handleFormSubmit을 function으로 바꿔서 진행했으므로
Form에서 handleFormSubmit이 아닌 updateMainCat을 prop으로 넘겨주었다.