Javascript 表单验证 - 电子邮件/电话号码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13628995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:31:57  来源:igfitidea点击:

Form Validation - Email/telephone number

javascripthtmlvalidation

提问by SadUnicorn

I have a problem with a validate function, I made it in one function only and I want to add validation of email such as @ and numbers 1-9. How do I add it?

我的验证函数有问题,我只在一个函数中实现了它,我想添加电子邮件验证,例如 @ 和数字 1-9。我如何添加它?

html:

html:

<form onsubmit="return validate();" name="formValidation">
    <label>First Name:</label>
    <input type="text" name="firstName" /><br /><br />
    <label>Last Name:</label>
    <input type="text" name="lastName" /><br /><br />
    <label>E_mail:</label>
    <input type="text" name="Email" /><br /><br />
    <label>Confirm E_mail:</label>
    <input type="text" name="confirmEmail" /><br /><br />
    <label>Address:</label>
    <input type="text" name="Address" /><br /><br />
    <label>Telephone nr:</label>
    <input type="text" name="telephoneNr" /><br /><br />
    <br />
    <p>submit your form: </p><input type="submit" value="Submit" />
</form>

js:

js:

function validate(){
    if(document.formValidation.firstName.value == "" ||
    document.formValidation.lastName.value == "" ||
    document.formValidation.Email.value == "" ||
    document.formValidation.confirmEmail.value == "" ||
    document.formValidation.Address.value == "" ||
    document.formValidation.telephoneNr.value == "")
    {
        alert("Please fill all the boxes before submitting!");
        return false;
    } else {
        alert('Your form has been submitted!');
    }

}

回答by GabCas

from http://www.w3resource.com/javascript/form/email-validation.php:

来自http://www.w3resource.com/javascript/form/email-validation.php

This function will validate an email using javascript:

此函数将使用 javascript 验证电子邮件:

function ValidateEmail(mail)   
{  
 if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(mail))  
  {  
    return (true)  
  }  
    alert("You have entered an invalid email address!")  
    return (false)  
}  

To validate a phone number:

要验证电话号码:

function validatePhone(phone) {
    var error = "";
    var stripped = phone.replace(/[\(\)\.\-\ ]/g, '');

   if (stripped == "") {
        error = "You didn't enter a phone number.";
    } else if (isNaN(parseInt(stripped))) {
        phone = "";
        error = "The phone number contains illegal characters.";

    } else if (!(stripped.length == 10)) {
        phone = "";
        error = "The phone number is the wrong length. Make sure you included an area code.\n";
    }
}

回答by AmericanUmlaut

You want to use a regular expression. There are a very large number of questions already describing how to do this:

您想使用正则表达式。已经有很多问题描述了如何做到这一点:

https://stackoverflow.com/search?q=javascript+regex+phone+number+email

https://stackoverflow.com/search?q=javascript+regex+phone+number+e​​mail

回答by vlex

I can give you an example function I've used. It's not perfect, but it's quick and easy to set in your environment with minimal editing:

我可以给你一个我用过的示例函数。它并不完美,但只需最少的编辑即可快速轻松地在您的环境中进行设置:

function mail_check(){
var email   = document.getElementById(\'email\').value;
var email_check = email.split("@");
if (email_check[1]){var email_check2 = email_check[1].split(".");}
if (!email_check[1] || !email_check2[0] || !email_check2[1]) {
document.getElementById(\'mail_status\').innerHTML = "<font color=red>Invalid Email address!</font>";
return false;}
else if (email_check[1] && email_check2[0] && email_check2[1]) {
document.getElementById(\'mail_status\').innerHTML = "<font color=green>Valid Email address!</font>";
return true;}
}

I guess it's obvious I have an empty span element, that gets altered live with an OnKeyUp js event (basically onkeyup calls the function, which creates the illusion the systems checks live... although it does, so I guess it's not an illusion after all - hah!)

我想很明显我有一个空的 span 元素,它被一个 OnKeyUp js 事件实时更改(基本上 onkeyup 调用该函数,这会产生系统实时检查的错觉......虽然确实如此,所以我想这不是错觉之后所有 - 哈!)

Hope that helps. In case you want further help let me know!

希望有帮助。如果您需要进一步的帮助,请告诉我!

Cheers!

干杯!

回答by dmi3y

This is quite common task, and way you trying solve it is what is was like a la 2008, hey it is 2013 almost here)

这是一项很常见的任务,您尝试解决它的方式就像 2008 年一样,嘿,几乎是 2013 年)

the first try to look up the regExpto solve it in this way.

第一次尝试查找regExp以这种方式解决它。

But yeh, why not use HTML5 form validationand Modernizirfor fallback on an older/unsupported browsers.

但是是的,为什么不使用 HTML5表单验证Modernizir在旧的/不受支持的浏览器上进行回退。

You will got native support for all modern browsers, which is faster than JS, plus well writen js which will care about it in a proper way for ones who by some reason do not have support for form validations.

您将获得对所有现代浏览器的原生支持,这比 JS 更快,加上编写良好的 js,它将以适当的方式关心由于某种原因不支持form validations.