gpt4 book ai didi

javascript - 添加到列表时验证表单中的电子邮件字段

转载 作者:行者123 更新时间:2023-11-30 17:32:00 25 4
gpt4 key购买 nike

我正在使用纯 js 将用户添加到列表中,我正在尝试使用 ajax 验证电子邮件字段。如何在提交表单之前验证电子邮件字段?如果电子邮件字段有效,那么我要提交,否则我会在有效电子邮件中显示错误。

这是代码

<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="text" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>


<h2>UsersList:</h2>
<ul id="users"></ul>

function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email').value;
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(username + ' ' + email));
list.appendChild(entry);
return false;
}

最佳答案

if you using js then below code will definitely help you.

if (document.getElementById('email').value != '')
{
reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(document.getElementById('email').value) == true) {

}
else {
alert("Please Enter Valid Email Id");
return false;
}

}
else{
alert("Please Enter Email Id");
return false;

}

edited code: u have to just replaced it with your code, hope will work for you:

function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email').value;
var entry = document.createElement('li');
if (email.value != '')
{
reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(email.value) == true) {
entry.appendChild(document.createTextNode(username + ' ' + email));
list.appendChild(entry);
return false;
}
else {
alert("Please Enter Valid Email Id");
return false;
}

}
else{
alert("Please Enter Email Id");
return false;

}

}

关于javascript - 添加到列表时验证表单中的电子邮件字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22828368/

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