必需属性不能与<form>标签一起使用

时间:2020-02-04 13:16:42

标签: javascript html css ajax required

我的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)

4 个答案:

答案 0 :(得分:2)

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>

答案 1 :(得分:2)

A属性不起作用,因为您的表单尚未提交。您需要指定带有requiredtype="submit"的按钮才能提交<input type="submit">

我建议您通过form事件在signUp标签内移动form函数:

onsubmit

然后将其添加到您的Javascript函数中:

<form onsubmit="signUp(event)">

答案 2 :(得分:2)

对我来说,我看到了许多可能的问题。我尝试使用以下示例代码删除它们。我假设/users将返回某事,该信息对于检查和提醒成员访问/users或处理数据时是否出错是有用的。

使用required的{​​{1}}属性在您的代码中没有任何明显作用,因为<input>有一个<button>调用,它将在浏览器检查之前触发。使用当前代码,表单值(存在或不存在)仍将发送到onclick=signUp(),因为没有测试这些值。

如果要运行浏览器检查,则需要将/users调用移至signUp()

要对此进行测试,请删除<form>中的onclick=signUp(),这将显示一个浏览器提示窗口,提示需要该值。

由于您坚持使用AJAX发布表单数据,因此将支票移至<button>提交是一种想法,而且个人而言,我仍然会检查这些值-只是一个好习惯。

下一个问题是您不等待<form>返回成功或失败响应。实际上,您是盲目地重定向到/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);
  }
}

答案 3 :(得分:0)

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>