gpt4 book ai didi

javascript - Javascript 中的表单验证

转载 作者:行者123 更新时间:2023-11-30 12:05:41 25 4
gpt4 key购买 nike

我似乎不太明白为什么我的代码在我单击提交按钮时不会给我返回错误或成功消息。我只是想验证 html 表单中的字符串,以确保它们不为空、不太大等。

开发人员的工具和在线 Lint 没有给我任何错误。希望你们能指出我写的任何不可靠的代码。

Javascript:

function submit()
{
var firstName = document.getElementById("fn");
var lastName = document.getElementById("ln");
var email = document.getElementById("email");
var emailR = document.getElementById("emailR");
var userName = document.getElementById("un");
var password = document.getElementById("pass");
var passwordR = document.getElementById("passR");
var error = "";
var letters = /^[a-zA-Z]+$/;
var postal = document.getElementById("pc");
var code = /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/;

if (firstName === null || firstName.length > 15 || !firstName.value.match(letters))
{
error += "Please enter a valid first name.";
}
if (lastName === null || lastName.length > 15 || !lastName.value.match(letters))
{
error += " Please enter a valid last name";
}

var ei = email.value.lastIndexOf('@');
var dot = email.value.lastIndexOf('.');
if (email === null || email.length < 7 || ei == -1 || dot == -1 || dot < ei + 2)
{
error += " Please enter a valid email address";
}
if (emailR != email)
{
error += " Your email addresses did not match";
}
if (postal === null || !postal.length == 7 || !postal.value.match(code))
{
error += "Postal code must follow Canadian standard. E.g. \"N3H 1M1\" ";
}
if (userName === null || userName.length > 15)
{
error += " Please enter a valid username (must be less than 15 characters)";
}
if (password === null || password.length > 15)
{
error += "please enter a valid password (must be less than 15 characters)";
}
if (passwordR != password)
{
error += "your passwords do not match";
}
if (error === "")
{
document.getElementById("test").innerHTML = "Thank you for signing up!";
}
else if (error !== "")
{
document.getElementById("test").innerHTML = error;
}
}

谢谢,Java新手

最佳答案

document.getElementById 为您提供完整的 HTMLElement 对象。要获取它的值,请使用它的 .value 属性。示例:

var email = document.getElementById("email").value;

(假设 id = "email" 的 HTML 元素是文本输入)

关于javascript - Javascript 中的表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35298940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com