【问题标题】:`Required` attribute not working with <form> tag`Required` 属性不适用于 <form> 标签
【发布时间】:2020-02-04 13:16:42
【问题描述】:

我的required 属性未指定在提交表单之前必须填写输入字段。

HTML:

<!-- Modal Content -->
            <form class="modal-content2">
                <div class="container3">
                    <h1>Sign Up</h1>
                    <p>Please fill in this form to create an account.</p>
                    <hr>
                    <label for="firstName"><b>First Name</b></label>
                    <input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>

                    <label for="lastName"><b>Last Name</b></label>
                    <input type="text" id="lastName" placeholder="Enter Last Name" name="lastName" required>

                    <label for="username"><b>Username</b></label>
                    <input type="text" id="username" placeholder="Enter Username" name="username" required>

                    <label for="email"><b>Email</b></label>
                    <input type="text" id="email" placeholder="Enter Email" name="email" required>

                    <label for="psw"><b>Password</b></label>
                    <input type="password" id="password" placeholder="Enter Password" name="psw" onfocus="this.value=''"
                        required>

                    <label for="psw-confirm"><b>Confirm Password</b></label>
                    <input type="password" id="cfmpassword" placeholder="Confirm Password" name="psw-confirm" onfocus="this.value=''"
                        required>

                    <br>
                    <br>
                    <p>By creating an account you agree to our <a href="aboutus.html" style="color:dodgerblue">Terms &
                            Privacy</a>.</p>

                    <div class="clearfix">
                        <button type="button" onclick="document.getElementById('id02').style.display='none'" class="cancelbtn2">Cancel</button>
                        <button type="button" class="signupbtn" onclick="signUp()">Sign Up</button>
                    </div>
                </div>
            </form>

JavaScript:

function signUp() {
    if (document.getElementById("password").value == document.getElementById("cfmpassword").value) {
        var users = new Object();
        users.firstName = document.getElementById("firstName").value;
        users.lastName = document.getElementById("lastName").value;
        users.username = document.getElementById("username").value;
        users.email = document.getElementById("email").value;
        users.password = document.getElementById("password").value;


        var postUser = new XMLHttpRequest(); // new HttpRequest instance to send user details

        postUser.open("POST", "/users", true); 

        postUser.setRequestHeader("Content-Type", "application/json");

        postUser.send(JSON.stringify(users));

        //go to the logged in page
        window.location = "main.html";
    }
    else {
        alert("Password column and Confirm Password column doesn't match!")
    }
}

由于required属性不起作用,用户可以连续提交空表单,这些表单将存储在我的SQL数据库中

我的表单中没有&lt;button type="submit"&gt;,因为这使我无法使用windows.location

我是编程新手,有人可以就如何解决这个问题提供一些建议(带有解释)吗?任何帮助,将不胜感激!非常感谢! (我为此使用香草 JavaScript)

【问题讨论】:

  • 你真的应该把代码放在问题里......
  • 好吧 onclick 不支持 html5 验证。
  • 表单中的buttons太多
  • 你从不使用 css 吗?
  • 如果你删除了这 3 行,就会出现 JavaScript 错误!如果你删除了这 3 行,就会出现 JavaScript 错误!为什么?因为您仍然在 Ajax 调用中使用credentials,这将引发错误。所以电话不会发生,提交将运行.... 像我在回答中建议的那样附上你的代码

标签: javascript html css ajax required


【解决方案1】:

对我来说,我看到了许多可能的问题。我尝试使用以下示例代码删除它们。我假设/users 将返回一些东西,如果访问/users 或处理数据时出现错误,则可用于检查和提醒会员。

使用&lt;input&gt;required 属性不会在您的代码中做任何明显的事情,因为&lt;button&gt; 有一个onclick=signUp() 调用,它将在浏览器检查之前触发。使用您当前的代码,表单值(存在与否)仍将发送到/users,因为没有对这些值进行测试。

如果您希望运行浏览器检查,您需要将 signUp() 调用移动到 &lt;form&gt;

要对此进行测试,删除 &lt;button&gt; 中的 onclick=signUp() 将显示一个浏览器提示窗口,提示您需要该值。

由于您坚持使用 AJAX 发布表单数据,因此将检查移至 &lt;form&gt; 提交是一个想法,而且就个人而言,我仍然会检查这些值 - 只是一种好的做法。

下一个问题是您没有等待来自/users 的成功或失败响应的返回。实际上,您是在盲目地重定向到main.html。如果有错误,用户永远不会知道。这是非常糟糕的用户体验。

通过检查带有回调的响应,检查响应值,然后在没有错误时提醒成员或重定向,在示例代码中对此进行了更正。

var users = {};

function ajaxPost(url,postData,callFunc) {
  var http = new XMLHttpRequest();
  if(! http){
   return false;
  }
  http.onreadystatechange=function(){
    if((http.readyState == 4) && (http.status == 200)) {
      if(callFunc){
        callFunc(http.responseText);
      }
    }
  }
  http.open('POST',url,true);
  http.send(postData);
}

function validResult(str) {
  if (str == "valid") {
    // go to the logged in page
    window.location = "main.html";
  } else {
    console.log("invalid result, let the user know");
  }
}

function signUp(e) {
  if(e){e.stopPropagation();e.preventDefault();}
  
  var d = document.getElementById("signupForm").querySelectorAll("input");
  var i, max = d.length;
  // Quick check for values only. No check for the format of the values.
  // This is good practice as a browser may still ignore the `required`
  // attribute.
  for(i=0;i<max;i++) {
    d[i].value = d[i].value.trim();
    if (d[i].value) {
      users[d[i].name] = d[i].value;
    } else {
      // An alert would be better for the user here.
      console.log("Missing value for ["+ d[i].name +"]");
      // Go no further if there is a missing value.
      return;
    }
  }
  // at this point, all values added to the users object.
  console.log("users:["+ JSON.stringify(users) +"]");
  // Send the data and wait for a return value from /users
  // --- remove comment on the following line to post ----
  //ajaxPost("/users",JSON.stringify(users),validResult);
}

window.onload = function(){
  var c = document.getElementById("signupForm");
  if (c) {
    c.addEventListener("submit",signUp,false);
  }
}
<form id="signupForm">
<label for="firstName"><b>First Name</b></label>
<input type="text" id="firstName" placeholder="Enter First Name" name="firstName" required>
<p>
<label for="email"><b>Email</b></label>
<input type="email" id="email" placeholder="Enter Email" name="email" required>
<p>
<button id="submit" type="submit">Check and submit</button>
</form>

【讨论】:

    【解决方案2】:

    required 属性不起作用,因为您的表单未提交。您需要指定一个带有type="submit"&lt;input type="submit"&gt; 的按钮来提交您的form

    我建议您将signUp 函数移动到form 标记内,像这样使用onsubmit 事件:

    &lt;form onsubmit="signUp(event)"&gt;

    然后将这个添加到你的 Javascript 函数中:

    function signUp(event) { event.preventDefault(); ... your old code }

    【讨论】:

      【解决方案3】:

      HTML5 验证的基础知识。您可以单击按钮并在验证发生之前运行它。这向您显示 onclick 运行而 onsubmit 不运行。使用正确的事件。

      function loginSubmit () {
        console.log('loginSubmit')
      }
      
      function loginClick () {
        console.log('loginClick')
      }
      <form onsubmit="loginSubmit()">
        <input name="foo" required />
        <button onclick="loginClick()">click</button>
      </form>

      【讨论】:

        【解决方案4】:

        required 属性的工作方式是确定其分配给的元素的值长度是否大于零,如果该语句为假(意味着值长度为零),则提交表单,它将将该元素作为其“必需”来完成。

        这是一个使用 JavaScript 的示例,以及如何在其中检查输入字段。

        const form   = document.querySelector('form[action="signup.php"]'); // Form
        const inputs = form.querySelectorAll('input');                      // All input elements inside the form
        const submit = form.querySelector('button[type="submit"]');         // Submit button inside the form
        
        // Add onclick event to the form button
        submit.addEventListener('click', function(event) {
        	event.preventDefault(); // This prevents the button from submitting the form the traditional way
        	submit_form();          // but instead our way
        });
        
        function submit_form()
        {
        	// We iterate through the form input elements
        	for (var i = 0; i < inputs.length; i++)
        	{
        		// We check if the current element has
        		// the attribute required and if so
        		// we proceed with checks
        		if (inputs[i].hasAttribute('required') && inputs[i].value.length == 0)
        		{
        			inputs[i].focus();                            // We focus on the required element
        			alert(inputs[i].placeholder+' is required!'); // Alert the user that the element is required
        			break;                                        // Break from the loop
        		}
        		else
        		{
        			if (i == (inputs.length - 1)) form.submit();  // If the loop's i variable counter hits the same value as the
        			                                              // input elements length then it means all fields are filled
        		}
        	}
        }
        form {
        	width:300px;
        	margin:auto
        }
        
        form button,
        form input {
        	width:100%;
        	height:48px;
        	padding:0 15px;
        	font-size:18px;
        	box-sizing:border-box;
        }
        
        form input:focus {
        	background-color:#f2dfb7;
        }
        <form action="signup.php" method="POST">
        	<input type="text" name="first_name" placeholder="First Name" required>
        	<input type="text" name="last_name" placeholder="Last Name" required>
        	<input type="email" name="email" placeholder="Email Address" required>
        	<input type="email" name="email_repeat" placeholder="Email Address (Repeat)" required>
        	<input type="password" name="password" placeholder="Password" required>
        	<input type="text" name="phone" placeholder="Phone Number" required>
        	<input type="text" name="birthday" placeholder="Birthday (MM/DD/YYYY)" required>
        	<button type="submit">Sign Up</button>
        </form>

        【讨论】:

          猜你喜欢
          • 2015-07-18
          • 1970-01-01
          • 1970-01-01
          • 2016-09-13
          • 2018-12-01
          • 1970-01-01
          • 2017-01-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多