简体   繁体   English

用javascript验证html表单

[英]validating html form with javascript

Basically I want to validate this form, I'm trying to do it with document.getElementByid(); 基本上我想验证这种形式,我试图用document.getElementByid();来完成document.getElementByid(); but it is not working can anyone help me with this and why it is not going the way that I'm trying. 但是它没有用,任何人都可以帮我解决这个问题,为什么它没有按照我尝试的方式进行。

 <form name="simple" action="POST">

            <label for="name">
                Name:
            </label>
            <input type="text" id="demo" class="form-control" onsubmit="validate();"><br>

            <label for="email">
                E-mail:
            </label>
            <input type="email" id="email" class="form-control"><br>

            <label for="pwd">
                Password:
            </label>
            <input type="password" id="pwd" class="form-control"><br>

            <label for="phone">
                Phone:
            </label>
            <input type="text" id="phone" class="form-control"><br>

            <input type="button" type="submit" value ="Submit" class="form-control" onclick="validate();" >

            <input type="button" type="reset" value ="Reset" class="form-control">

        </form>
        <script>


        function validate()
    {
        var txt = document.getElementById("demo");
        alert(txt);
        if(txt == " " || txt == null)
        {
            alert("Name can't be left blank");
        }

    }
        </script>

In order to get the value of a field, you have to access the .value field of the element, like so: document.getElementById('demo').value . 为了获取字段的值,您必须访问元素的.value字段,例如: document.getElementById('demo').value

In order to catch the submit event, you must set the onsubmit function on the form, like so: 为了赶上submit事件,您必须在表单上设置onsubmit函数,如下所示:

document.getElementById("myform").onsubmit = validate;

Inside the validate function, you have to call return false; 在validate函数内部,必须调用return false; in case the input is invalid: 如果输入无效:

if (txt === null || txt.trim() === '') {
    alert("Name can't be left blank");
    return false;
}

Also, if you're doing validation, look into the pattern and required attributes of the input element. 另外,如果要进行验证,请查看input元素的patternrequired属性。 All modern browsers will respect the rules you set with these attributes, and you wouldn't have to manually validate it. 所有现代的浏览器都将遵守您使用这些属性设置的规则,而无需手动验证它。

https://www.w3schools.com/tags/att_input_pattern.asp https://www.w3schools.com/tags/att_input_required.asp https://www.w3schools.com/tags/att_input_pattern.asp https://www.w3schools.com/tags/att_input_required.asp

The @user337554 is correct, I just want to show you another approach, it's valid to say when we are taking care about forms/fields handling. @ user337554是正确的,我只想向您展示另一种方法,可以说我们在处理表单/字段处理时是正确的。

Using JavaScript in it's traditional form, you can mind in using the form's onsubmit event to trigger the validation and wait it's return to proceed or not with the POST / GET you want. 使用传统形式的JavaScript,您可以介意使用表单的onsubmit事件来触发验证,并等待其返回以继续执行所需的POST / GET。

The DOM node structure enable you to access fields by it's respective names using something like document.form_name.field_name . DOM节点结构使您可以使用诸如document.form_name.field_name类的字段名称来访问字段。

In my example I've passed the form itself as parameter to the validation function, so you will handle it as the native DOM form object with all it's features and children. 在我的示例中,我将表单本身作为参数传递给了验证函数,因此您将把它作为具有所有功能和子元素的本地DOM表单对象进行处理。

Hope it helps you in minding about possibilities in your code, I like that because I can make it cleaner and I can use the DOM tree instead of millions getElementByID . 希望它可以帮助您考虑代码中的可能性,我喜欢这样做,因为我可以使其变得更整洁,并且可以使用DOM树代替数百万的getElementByID

You can run the code below, it works: 您可以运行下面的代码,它可以正常工作:

 /** * Triggered by the form's onsubmit event */ function validate(form) { console.info("Beginning the validation.."); // Validating the fields by the DOM nodes sequence from form to input names if(form.demo.value == "") { alert("Name can't be left blank"); return false; // Quit the POST } if(form.email.value == "") { alert("E-mail can't be left blank"); return false; // Quit the POST } if(form.pwd.value == "") { alert("Password can't be left blank"); return false; // Quit the POST } if(form.phone.value == "") { alert("Phone can't be left blank"); return false; // Quit the POST } console.info("Finished!"); // Form is OK return true; } 
 <form action="#" name="simple" action="POST" onsubmit="return validate(this)"> <label for="name"> Name: </label> <input type="text" id="demo" name="demo" class="form-control"><br> <label for="email"> E-mail: </label> <input type="email" id="email" name="email" class="form-control"><br> <label for="pwd"> Password: </label> <input type="password" id="pwd" name="pwd" class="form-control"><br> <label for="phone"> Phone: </label> <input type="text" id="phone" name="phone" class="form-control"><br> <!-- IT'S WRONG, YOU HAVE 2 TYPES HERE, USE SUBMIT TO INTERCEPT THE EVENT <input type="button" type="submit" value ="Submit" class="form-control" > --> <input type="submit" value ="Submit" class="form-control" > <input type="button" type="reset" value="Reset" class="form-control"> </form> 

Use this 用这个

function validate() {
  txt = document.getElementById("demo");
  alert(txt);
  if(txt.value.trim() == "" || txt.value == null)
  {
      alert("Name can't be left blank");
  }
}

Note: The keyword var is not present before the txt variable. 注意:关键字vartxt变量之前不存在。 The value fetches the value of the input field with id demo . value使用id demo获取输入字段的值。 The trim() function trims the leading/trailing spaces to ensure the input is not just white space character/s. trim()函数会修剪前导/尾随空格,以确保输入不只是空格字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM