javascript表单验证不为空或没有空格

时间:2014-12-18 09:52:37

标签: javascript html validation

我试图验证表单即时创建并且似乎无法理解这是如何工作我试图确保字段inst为空或不包含空格我已验证它服务器端而不是客户端

有人可以告诉我下面的代码,以验证是否为空或没有空格

我在下面看到这些,这就是我认为他们做的事情

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

我提前感谢您的帮助



<!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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

您可以使用javascript 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>