用javascript验证表单

时间:2018-08-11 00:51:17

标签: javascript html

这是表格的代码:

<form>
    <h1>Michael</h1>
    <ul style="list-style-type: none;">
        <li>Name:
            <input type="text" id="username" size="30" maxlength="40">
        </li>
        <li>&nbsp;</li>
        <li>Password:
            <input type="password" id="password" size="30" maxlength="40">
        </li>
        <li>
            <li>&nbsp;</li>
            <input type="button" id="submit" value="Submit" onclick="check()">
        </li>
        <li>&nbsp;</li>
    </ul>
</form>

这是验证码:

function check() {
    if (document.getElementById("username").value = "username") {
        if (document.getElementById("password").value = "password") {
            window.location.href = "wreck.html";
        }
    }
    else {
        document.location.reload(true);
    }
}

我想验证表格,如果用户名和密码正确,则转到特定页面。有什么建议吗?

3 个答案:

答案 0 :(得分:1)

您应该重新考虑您的策略。

您的check()函数的javascript代码将由每位访问者下载并查看。

这意味着您当前的方法将:

  1. 公开显示访问者的用户名和密码。
  2. 允许任何访问者将自己重定向到您的登录表单后面的任何内容。

虽然可以在客户端执行基本验证(输入的内容或格式正确),但是应该在服务器端始终执行用户凭证的验证。

如果您要通过客户端功能执行此操作,而不是正常发布表单...

  1. 该函数应通过ajax调用将表单输入提交给服务器。
  2. 服务器端功能应执行验证,响应应包括所需的重定向位置。

答案 1 :(得分:0)

在代码中,如果您发现自己在if语句中使用赋值 = 运算符,而不是相等的 === 运算符。

应该是

if (document.getElementById("username").value === "username") {
    if (document.getElementById("password").value === "password") {
        window.location.href = "wreck.html";
    }
}

答案 2 :(得分:0)

首先,我们使用香草JS完成所有繁重的工作。之后,我们使用一些CSS为其提供适当的样式和验证标志,最后,我们进行基本的HTML标记。不要忘记匹配所有ID。在这里,我进行了电子邮件验证,但是可以使用if statements通过检查长度,类型等来将相同的原理应用于您的用户名,密码等。运行代码片段,看看是否适合您。我真的希望它能做到:)

// There are fewer ways to pick a DOM node with legacy browsers
var form  = document.getElementsByTagName('form')[0];
var email = document.getElementById('mail');

 document.getElementById("myForm").onsubmit = function() {
     alert(document.getElementById("mail").value);
 }

// The following is a trick to reach the next sibling Element node in the DOM
// This is dangerous because you can easily build an infinite loop.
// In modern browsers, you should prefer using element.nextElementSibling
var error = email;
while ((error = error.nextSibling).nodeType != 1);

// As per the HTML5 Specification
var emailRegExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;

// Many legacy browsers do not support the addEventListener method.
// Here is a simple way to handle this; it's far from the only one.
function addEvent(element, event, callback) {
  var previousEventCallBack = element["on"+event];
  element["on"+event] = function (e) {
    var output = callback(e);

    // A callback that returns `false` stops the callback chain
    // and interrupts the execution of the event callback.
    if (output === false) return false;

    if (typeof previousEventCallBack === 'function') {
      output = previousEventCallBack(e);
      if(output === false) return false;
    }
  }
};

// Now we can rebuild our validation constraint
// Because we do not rely on CSS pseudo-class, we have to 
// explicitly set the valid/invalid class on our email field
addEvent(window, "load", function () {
  // Here, we test if the field is empty (remember, the field is not required)
  // If it is not, we check if its content is a well-formed e-mail address.
  var test = email.value.length === 0 || emailRegExp.test(email.value);

  email.className = test ? "valid" : "invalid";
});

// This defines what happens when the user types in the field
addEvent(email, "input", function () {
  var test = email.value.length === 0 || emailRegExp.test(email.value);
  if (test) {
    email.className = "valid";
    error.innerHTML = "";
    error.className = "error";
  } else {
    email.className = "invalid";
  }
});

// This defines what happens when the user tries to submit the data
addEvent(form, "submit", function () {
  var test = email.value.length === 0 || emailRegExp.test(email.value);

  if (!test) {
    email.className = "invalid";
    error.innerHTML = "I expect an e-mail, darling!";
    error.className = "error active";

    // Some legacy browsers do not support the event.preventDefault() method
    return false;
  } else {
    email.className = "valid";
    error.innerHTML = "";
    error.className = "error";
  }
});
/* This is just to make the example nicer */
body {
  font: 1em sans-serif;
  padding: 0;
  margin : 0;
}

form {
  max-width: 200px;
}

p * {
  display: block;
}

input.mail {
  -webkit-appearance: none;

  width: 100%;
  border: 1px solid #333;
  margin: 0;

  font-family: inherit;
  font-size: 90%;

  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

/* This is our style for the invalid fields */
input.invalid{
  border-color: #900;
  background-color: #FDD;
}

input:focus.invalid {
  outline: none;
}

/* This is the style of our error messages */
.error {
  width  : 100%;
  padding: 0;
 
  font-size: 80%;
  color: white;
  background-color: #900;
  border-radius: 0 0 5px 5px;
 
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

.error.active {
  padding: 0.3em;
}
<form id="myForm">
  <p>
    <label for="mail">
        <span>Please enter an valid email address:</span>
        <input type="text" class="mail" id="mail" name="mail">
        <span class="error" aria-live="polite"></span>
    </label>
  <p>
  <!-- Some legacy browsers need to have the `type` attribute
       explicitly set to `submit` on the `button`element -->
  <button type="submit">Submit</button>
</form>

相关问题