我被分配了一项任务,为假设的培训业务制作注册页面。
我目前正在为名字输入创建表单验证,它检查该字段是否为空、是否等于占位符、是否包含任何数字或特殊字符。但是,当我单击我的 button 元素(不是输入类型=提交)时,我的代码没有响应。
预期结果是字体颜色更改为粉红色,内部文本显示“请输入有效的名字”。
我尝试在 JavaScript 中调用表单
form.addEventListener("submit", newCustomer);
和按钮 tn.addEventListener("submit", newCustomer);
,但没有任何反应。
div class="form-container">
<form action="" id="form">
<div class="form-top">
<div class="title">
<label for="firstname" class="firstname">First Name:</label>
<label for="lastname" class="lastname">Last Name:</label>
<label for="email address" class="email-address">Email:</label>
<label for="card details " class="card-details"> Card:</label>
</div>
<div class="textbox">
<input type="text" placeholder="Enter Your Firstname" id="f-name">
<input type="text" placeholder="Enter Your Last Name" id="l-name">
<input type="text" placeholder="Enter Your Email" id="email">
<input type="text" placeholder="Enter a Proxy Credit Card Number" id="card">
</div>
</div>
<div class="button-container"><button id="btn" type="submit">Submit</button></div>
</form>
<script>
var fname = document.getElementById("f-name");
var lname = document.getElementById("l-name");
var email = document.getElementById("email");
var card = document.getElementById("card");
const btn = document.getElementById("btn");
const form = document.getElementById("form");
var Customers = [];
function newCustomer(event, firstname, lastname, emailAddress, cardNum) {
event.preventDefault();
firstname = fname;
lastname = lname;
emailAddress = email;
cardNum = card;
if (firstname === "" || firstname.placeholder === "Enter Your Firstname") {
firstname.innerText = "Please enter a valid first name";
firstname.style.color = "rgb(231,0,100)";
} else {
var specialChars = /[!@#$%^&*(),.?":{}|<>]/g;
for (let i = 0; i < firstname.value.length - 1; i++) {
if (!isNaN(firstname[i])) {
firstname.placeholder.style.color = "rgb(231,0,100)";
firstname.placeholder.innerText = "Please enter a valid first name";
} else if (specialChars.test(firstname[i]) == true) {
firstname.style.color = "rgb(231,0,100)";
firstname.innerText = "Please enter a valid first name";
} else {
firstname.style.color = "rgb(137,200,46)";
form.reset();
}
}
}
}
btn.addEventListener("submit", newCustomer);
</script>
</div>
在表单标签中添加 onSubmit = "newCustomer"
<form onSubmit = "newCustomer"> </form>