The validation is working correctly, however when the user fails the validation the default action is still carried out.(验证工作正常,但是当用户验证失败时,仍将执行默认操作。)
So validation fails and the joke is still returned.(因此验证失败,并且该笑话仍然返回。) If validation fails, the Joke should not be returned.(如果验证失败,则不应返回该笑话。) I have tried to use preventDefault but no luck.(我试图使用preventDefault但没有运气。) import React, { useState } from "react";
function Search() {
const [joke, setJoke] = useState()
const [firstname, setFN] = useState("sharoze")
const [lastname, setLN] = useState("khan")
const newJoke = (first, last) => {
fetch(`http://api.icndb.com/jokes/random?firstName=${first}&lastName=${last}`)
.then(result => result.json())
.then(result2 => {
console.log(result2)
setJoke(result2.value.joke)
})
}
function validateForm() {
var firstname = document.getElementsByName("firstname")[0].value;
var lastname = document.getElementsByName("lastname")[0].value;
if (firstname === "" && lastname === "") {
alert("Please enter atleast one name");
}
else if (!(/^[a-zA-Z]+$/.test(firstname + lastname))) {
alert("'Only alphabets allowed'");
}
}
return (
<div className="jokeForm" >
<form name="searchForm" >
<input type="text" name="firstname" placeholder="First name" value={firstname} onChange={(e) => setFN(e.target.value)} />
<input type="text" name="lastname" placeholder="Last name" value={lastname} onChange={(e) => setLN(e.target.value)} />
</form>
<button id="button" onClick={(e) => { validateForm(newJoke(firstname, lastname)); return false; }}>click here for a personalised chuckle</button>
<h3>{joke}</h3>
</div >
)
}
export default Search;
sorry the code has been a little butchered!(抱歉,该代码已被取消了!)
ask by Sharoze Khan translate from so