`Required` 属性不适用于 <form> 标签

`Required` attribute not working with <form> tag

我的 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 数据库中

我在表单中没有 <button type="submit">,因为这使我无法使用 windows.location

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

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>

required 属性不起作用,因为您的表单未提交。您需要指定带有 type="submit"<input type="submit"> 的按钮来提交您的 form.

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

<form onsubmit="signUp(event)">

然后给你添加这个Javascript函数:

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

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

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

如果您希望浏览器检查为 运行,您需要将 signUp() 调用移动到 <form>

要对此进行测试,删除 <button> 中的 onclick=signUp() 将显示一个浏览器提示 window,说明需要该值。

由于您坚持使用 AJAX 来 post 表单数据,因此将检查移至 <form> 提交是一个想法,就个人而言,我仍然会检查这些值 -很好的练习。

下一个问题是您没有等待 /users 的成功或失败响应 return。事实上,你是在盲目地重定向到 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>

required 属性的工作方式是确定它分配给的元素的值长度是否大于零,如果该语句为假(意味着值长度为零)然后在提交表单时它将该元素聚焦为要实现的 "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>