Javascript form validation not empty or no spaces

im trying to validate the form im creating and cant figure out how this work im trying to make sure the inst field is empty or contains no spaces, i validated it server side but not client side.

can someone please show me the code as below to confirm that it is empty or has no spaces.

I see it below and this is what I thought they did

x===null // means if field is empty
x===""  // on trying this means if the field is empty
x===" " // and this checks if there is 1 white space

      

I appreciate your help in advance

<!DOCTYPE html>
    <html>
    <head>
    <script>
    function validateForm() {
        var x = document.forms["myForm"]["fname"].value;
        if (x===null || x===""|| x===" ") {
            alert("First name must be filled out");
            return false;
        }
    }
    </script>
    </head>
    
    <body>
    <form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
    First name: <input type="text" name="fname">
    <input type="submit" value="Submit">
    </form>
    </body>
    
    </html>
      

Run codeHide result


+3


source to share


1 answer


You can do it using javascript function trim()

.



<!DOCTYPE html>
    <html>
    <head>
    <script>
    function validateForm() {
        var x = document.forms["myForm"]["fname"].value;
        if (x.trim()==null || x.trim()==""|| x===" ") {
            alert("First name must be filled out");
            return false;
        }
    }
    </script>
    </head>
    
    <body>
    <form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
    First name: <input type="text" name="fname">
    <input type="submit" value="Submit">
    </form>
    </body>
    
    </html>
      

Run codeHide result


+3


source







All Articles