How to check empty/undefined/null string in JavaScript?

If we want to check any string either it is filled or empty we can use Javascript for such purpose for example : form validation.
Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE HTML>
<html>
  
<head>
    <!--function to check that name can not be empty-->
    <script>
        function checkempty(form) {
            if (form.name.value == null || 
                form.name.value == undefined ||
                form.name.value.length == 0) {
                
                alert("Name cannot be empty\n");
                return false;
            } else {
                alert("Your response has been recorded\n");
                return true;
            }
        }
    </script>
</head>
  
<body>
    <div>
        <center>
            <form onsubmit="return checkempty(form1)"
                  action="#" method="post"
                  name="form1">
                <label>Enter your name</label>
                <br>
                <input type="string"
                       placeholder="Enter name"
                       name="name" />
                <br>
                <br>
                <label>Enter Email</label>
                <br>
                <input type="" 
                       placeholder="Enter email"
                       name="email" />
                <br>
                <br>
                <label>Enter password</label>
                <br>
                <input type="password" 
                       placeholder="Enter password "
                       name="password1" />
                <br>
                <br>
                <label>Confirm password</label>
                <br>
                <input type="password"
                       placeholder="Enter password " 
                       name="password2" />
                <br>
                <br>
                <input type="submit" 
                       value="submit" />
                <br>
            </form>
        </center>
    </div>
</body>
  
</html>

chevron_right


Output:
If the name is empty:

After submitting the form:



My Personal Notes arrow_drop_up

I am a quick learner and eager to learn new technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.