Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Simple way to validate an empty text box on submit

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 814
    Comment on it

    Validating an empty field on submit through JavaScript

    As we know in almost all the web applications we have forms which contain text boxes and text fields to input some data and submit it. Sometimes knowingly or unknowingly users can submit the form without entering any data into the input field which can create an empty block in the database leading to errors.

    To avoid this kind of situation we can set some validations to our text fields and not let the form to be submitted unless and until the required fields are not filled. To achieve this validation we can use javascript as follows:

    • In this below code, we have created a form which contains a text area field where the user can input some data
    • After that, there is a submit button which will submit this data at the backend to the server.
    • On this submit button we have called a function named check. We will create this function in the script

    tags and perform our validation out there.

    • And above all, we have created a p tag in which we will display our error if the user will submit an empty textarea field.

    let your HTML form be like this : 

        <form action="", name="", method="">
          <p style="color: red;" id="comment_error"></p>
          <textarea rows="3" id="comment_box" name=""></textarea>
          <input type="submit" name="commit" value="Post Comment"
            onclick="return check()">


    • In the below code we will write the javascript code in the script tags. This tag will contain the function check which we have called on the onclick method of our submit button.
    • The onclick function on the submit button will take the control to the function check defined in the script tags. 
    • In that function, we got the value of text box in a variable x. And then we will check if the value is null or empty. if it would be empty then we have set the text of the p tag by calling it through its Id.

    Javascript code should be like this : 

    function check(){
        var x = document.getElementById('comment_box').value
        if (x == null || x == "") {
          document.getElementById('comment_error').innerHTML = "*The box cant be left blank!";
          return false

    This is how we can validate simple input fields through javascript for client side validations.

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: