Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

javascript - 提交验证失败(validation fails on submit)

The code should validate that the input fields dont contain a number and only letters and also both fields arent blank.(该代码应验证输入字段不包含数字,仅包含字母,并且两个字段均不包含空格。)

Currently it works with detecting if they aren't blank but it only detects a number in 'firstname' - I have managed to get one or the other working but never both at the same time.(目前,它可以检测它们是否不为空,但只能检测“名字”中的数字-我设法使一个或另一个工作正常,但从未同时工作过。) Help!!(救命!!) Also, If the validation fails the joke shouldn't be returned (the button onclick provides the joke by using the first and last name and sending it to an api to retrieve the joke).(另外,如果验证失败,则不应返回该笑话(onclick按钮通过使用名字和姓氏并将其发送到api来检索该笑话来提供该笑话)。) function validateForm() { var firstname = document.getElementsByName("firstname")[0].value; var lastname = document.getElementsByName("lastname")[0].value; var input = document.getElementsByName("firstname" && "lastname"); 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 onClick={() => validateForm(newJoke(firstname, lastname))}>click here for a personalised chuckle</button> <h3>{joke}</h3> </div > ) }   ask by Sharoze Khan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use + to add both strings together.(使用+将两个字符串加在一起。)

And do test with Regex.(并使用Regex进行测试。) eg.(例如。) var firstname="j"; var lastname="k1"; if (!(/^[a-zA-Z]+$/.test(firstname + lastname))) { alert("Only alphabets allowed!"); }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...