简体   繁体   中英

JS form validation to ensure that if a name is not entered a pop-up appears

The idea is that when the user is presented with the What is your name box, if they don't fill it in they would get a pop up message saying "please enter your name".

I don't understand why the form does not return the pop-up as I am calling the correct getElementsByName method I believe and checking if a value has been entered. I have tried changing the elementsByName to ("name") and ("UserInfo") but nothing happens. Does anyone have any ideas what might be the issue? I know the submit button is missing from the form but that was intentional as otherwise I'd have to post more code than necessary.

The code snippet is attached. The function name in html is called validate();

ALSO, I CANNOT MAKE ANY CHANGES TO THE HTML, IT NEEDS TO REMAIN AS IS.

 function Validate() { alert(document.getElementsByName("UserInfo")[0].value); if (name == "" || name == null) { alert('Please enter a name'); return false; } else { return true; } }
 <h2>A Simple Quiz</h2> <fieldset> <legend>About You</legend> <p id="UserInfo">What is your name?</p> <div> <input type="text" name="UserInfo" size="40" /> </div> </fieldset>

You are checking for name to be empty or null but the variable name isn't defined hence its always executing the else part.

Below is the working model of your snippet. I had assigned the input value to value and check for existence, do alert if not a valid input.

 function Validate(){ const value = document.getElementsByName("UserInfo")[0].value; if(;value) { alert('Please enter a name'); return false; } else { return true; } }
 <h2>A Simple Quiz</h2> <form onsubmit="Validate()"> <fieldset> <legend>About You</legend> <p id="UserInfo">What is your name?</p> <div> <input type="text" name="UserInfo" size="40" required /> <button type="submit">Submit</button> </div> </fieldset> </form>

UPDATE: Use required attribute.

Even better approach would be to wrap all the elements and submit button inside form and add required attribute to all required elements. Updated the answer.

Adding required will abort the submit itself.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM