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 :
<!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
filter_none
Output:
If the name is empty:

After submitting the form:

Recommended Posts:
- JavaScript | Check if a string is a valid JSON string
- JavaScript | Check if a variable is a string
- How to check if string contains only digits in JavaScript ?
- How to check if a string is html or not using JavaScript?
- How to check a string is entirely made up of the same substring in JavaScript ?
- JavaScript | Check if a string is a valid hex color representation
- JavaScript | Difference between String.slice and String.substring
- How to count string occurrence in string using JavaScript?
- JavaScript | Insert a string at position X of another string
- PHP | Program to check a string is a rotation of another string
- Substring check in JavaScript
- How to Check/Uncheck the checkbox using JavaScript ?
- How to check if a variable is an array in JavaScript?
- How to check an object is empty using JavaScript?
- How to check whether an object exists in javascript ?
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.



