Programing

jQuery를 사용한 이메일 검증

lottogame 2020. 3. 4. 08:08
반응형

jQuery를 사용한 이메일 검증


jQuery를 처음 사용하고 이메일 주소를 확인하는 데 사용하는 방법이 궁금합니다.


이를 위해 일반적인 오래된 자바 스크립트를 사용할 수 있습니다.

function isEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}

이메일을 검증하는 jQuery 함수

특히 양식에 유효성 검사가 필요한 필드가 하나만있는 경우 플러그인을 사용하고 싶지 않습니다. 이 기능을 사용하여 전자 메일 양식 필드의 유효성을 검사해야 할 때마다 호출합니다.

 function validateEmail($email) {
  var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
  return emailReg.test( $email );
}

그리고 지금 이것을 사용

if( !validateEmail(emailaddress)) { /* do stuff here */ }

건배!


몇 가지 이유로 jQuery 유효성 검사 플러그인사용합니다 .

당신은 확인, 좋아, 지금 무엇? 오류를 표시하고, 유효 할 때 지우기를 처리하고, 총 오류 수를 표시해야합니까? 휠을 다시 발명 할 필요가없는 많은 것들이 당신을 위해 처리 할 수 ​​있습니다.

또한 CDN에서 호스팅되는 또 다른 큰 이점은 이 답변 당시의 현재 버전 여기에서 찾을 수 있습니다. http://www.asp.net/ajaxLibrary/CDNjQueryValidate16.ashx 이는 클라이언트의로드 시간이 더 빠름을 의미합니다.


에서 봐 HTTP : //bassistance.de/jquery-plugins/jquery-plugin-validation/ . 양식에 대한 강력한 유효성 검사 시스템을 구축 할 수있는 멋진 jQuery 플러그인입니다. 여기에 유용한 샘플이 있습니다 . 따라서 전자 메일 필드 유효성 검사 형식은 다음과 같습니다.

$("#myform").validate({
  rules: {
    field: {
      required: true,
      email: true
    }
  }
});

자세한 내용과 샘플 이메일 방법 설명서참조하십시오 .


<script type="text/javascript">
    $(document).ready(function() {
      $('.form_error').hide();
      $('#submit').click(function(){
           var name = $('#name').val();
           var email = $('#email').val();
           var phone = $('#phone').val();
           var message = $('#message').val();
           if(name== ''){
              $('#name').next().show();
              return false;
            }
            if(email== ''){
               $('#email').next().show();
               return false;
            }
            if(IsEmail(email)==false){
                $('#invalid_email').show();
                return false;
            }

            if(phone== ''){
                $('#phone').next().show();
                return false;
            }
            if(message== ''){
                $('#message').next().show();
                return false;
            }
            //ajax call php page
            $.post("send.php", $("#contactform").serialize(),  function(response) {
            $('#contactform').fadeOut('slow',function(){
                $('#success').html(response);
                $('#success').fadeIn('slow');
               });
             });
             return false;
          });
      });
      function IsEmail(email) {
        var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if(!regex.test(email)) {
           return false;
        }else{
           return true;
        }
      }
  </script>

<form action="" method="post" id="contactform">
                            <table class="contact-table">
                              <tr>
                                <td><label for="name">Name :</label></td>
                                <td class="name"> <input name="name" id="name" type="text" placeholder="Please enter your name" class="contact-input"><span class="form_error">Please enter your name</span></td>
                              </tr>
                              <tr>
                                <td><label for="email">Email :</label></td>
                                <td class="email"><input name="email" id="email" type="text" placeholder="Please enter your email" class="contact-input"><span class="form_error">Please enter your email</span>
                                  <span class="form_error" id="invalid_email">This email is not valid</span></td>
                              </tr>
                              <tr>
                                <td><label for="phone">Phone :</label></td>
                                <td class="phone"><input name="phone" id="phone" type="text" placeholder="Please enter your phone" class="contact-input"><span class="form_error">Please enter your phone</span></td>
                              </tr>
                              <tr>
                                <td><label for="message">Message :</label></td>
                                <td class="message"><textarea name="message" id="message" class="contact-input"></textarea><span class="form_error">Please enter your message</span></td>
                              </tr>
                              <tr>
                                <td></td>
                                <td>
                                  <input type="submit" class="contactform-buttons" id="submit"value="Send" />
                                  <input type="reset" class="contactform-buttons" id="" value="Clear" />
                                </td>
                              </tr>
                            </table>
     </form>
     <div id="success" style="color:red;"></div>

<!-- Dont forget to include the jQuery library here -->
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {

    $("#validate").keyup(function(){

        var email = $("#validate").val();

        if(email != 0)
        {
            if(isValidEmailAddress(email))
            {
                $("#validEmail").css({
                    "background-image": "url('validYes.png')"
                });
            } else {
                $("#validEmail").css({
                    "background-image": "url('validNo.png')"
                });
            }
        } else {
            $("#validEmail").css({
                "background-image": "none"
            });         
        }

    });

});

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

</script>

<style>
    #validEmail
    {
        margin-top: 4px;
        margin-left: 9px;
        position: absolute;
        width: 16px;
        height: 16px;
    }

    .text
    {
        font-family: Arial, Tahoma, Helvetica;
    }
</style>

    <title>Live Email Validation with jQuery Demo</title>
</head>
<body>
    <div class="text"><h1>Reynoldsftw.com - Live Email Validation</h1><h2>Type in an email address in the box below:</h2></div>
    <div><input type="text" id="validate" width="30"><span id="validEmail"></span></div>
    <div class="text"><P>More script and css style

: www.htmldrive.net


출처 : htmldrive.com


Verimail.js를 추천 하고 JQuery 플러그인도있다 .

왜? Verimail은 다음을 지원합니다.

  • 구문 유효성 검사 (RFC 822에 따름)
  • IANA TLD 검증
  • 가장 일반적인 TLD 및 이메일 도메인에 대한 맞춤법 제안
  • mailinator.com과 같은 임시 이메일 계정 도메인 거부

따라서 Verimail.js는 유효성 검사 외에도 제안 사항을 제공합니다. 따라서 일반적인 전자 메일 도메인 (hotmail.com, gmail.com 등)과 매우 유사한 잘못된 TLD 또는 도메인이있는 전자 메일을 입력하면이를 감지하여 수정을 제안 할 수 있습니다.

예 :

  • test@gnail.con-> test @ gmail.com 을 의미 했습니까 ?
  • test@hey.nwt-> test @ hey를 의미 했습니까? 그물 ?
  • test@hottmail.com-> test @ hotmail.com 을 의미 했습니까 ?

등등..

jQuery와 함께 사용하려면 사이트에 verimail.jquery.js포함 시키고 아래 함수를 실행하십시오.

$("input#email-address").verimail({
    messageElement: "p#status-message"
});

메시지 요소는 메시지가 표시 될 요소입니다. "이메일이 유효하지 않습니다"에서 "의미 되었습니까?"까지 모든 것이 될 수 있습니다.

양식이 있고 이메일이 유효하지 않으면 제출할 수 없도록 제한하려는 경우 아래에 표시된대로 getVerimailStatus-function을 사용하여 상태를 확인할 수 있습니다.

if($("input#email-address").getVerimailStatus() < 0){
    // Invalid
}else{
    // Valid
}

이 함수는 Comfirm.AlphaMail.Verimail.Status 객체에 따라 정수 상태 코드를 반환합니다. 그러나 일반적으로 0 미만의 코드는 오류를 나타내는 코드입니다.


function isValidEmailAddress(emailAddress) {
    var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
    return pattern.test(emailAddress);
};

if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here (email is invalid) */ }

이것은 사용자가 제공 한 루카 Filosofi 이 대답 이 답변


이는보다 철저한 유효성 검사를 수행합니다 (예 : john..doe @ example.com과 같은 사용자 이름의 연속적인 점을 검사 함)

function isValidEmail(email)
{
    return /^[a-z0-9]+([-._][a-z0-9]+)*@([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,4}$/.test(email)
        && /^(?=.{1,64}@.{4,64}$)(?=.{6,100}$).*/.test(email);
}

JavaScript에서 정규식을 사용하여 이메일 주소 확인을 참조하십시오 .


매우 간단한 해결책은 html5 유효성 검사를 사용하는 것입니다.

<form>
  <input type="email" required pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}">

  <input type="submit">
</form>

http://jsfiddle.net/du676/56/


기본 양식이 있다면 입력 유형의 이메일을 만드십시오. <input type="email" required>

이것은 HTML5 속성을 사용하는 브라우저에서 작동하며 JS가 필요하지 않습니다. 위의 스크립트 중 일부와 함께 이메일 유효성 검사를 사용하는 것만으로는 그다지 중요하지 않습니다.

some@email.com so@em.co my@fakemail.net

등 ... 모두 "실제"이메일로 확인됩니다. 따라서 동일한 주소를 입력하기 위해 사용자가 자신의 전자 메일 주소를 두 번 입력해야하는 것이 더 나을 것입니다. 그러나 전자 메일 주소가 실제임을 보장하는 것은 매우 어렵지만 방법. 그러나 이메일인지 확인하려면 HTML5 입력을 사용하십시오.

피들 예제

FireFox 및 Chrome에서 작동합니다. 인터넷 익스플로러에서는 작동하지 않을 수 있습니다 ... 그러나 인터넷 익스플로러는 짜증납니다. 그럼 ...


function isValidEmail(emailText) {
    var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
    return pattern.test(emailText);
};

이렇게 사용 :

if( !isValidEmail(myEmail) ) { /* do things if myEmail is valid. */ }

MVC / ASP.NET의 자바 스크립트 이메일 유효성 검사

Fabian의 답변을 사용하면서 내가 겪은 문제는 면도기 @기호로 인해 MVC보기로 구현하는 것입니다 . @이스케이프 하려면 추가 기호 를 포함시켜야합니다 .@@

MVC에서 면도기를 피하려면

function isEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}

이 페이지의 다른 곳에서는 볼 수 없었으므로 도움이 될 것이라고 생각했습니다.

편집하다

다음은 사용법을 설명하는 Microsoft 링크 입니다.
방금 위 코드를 테스트하고 다음 js를 얻었습니다.

function validateEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
  return regex.test(email);
}

정확히해야 할 일을하는 것입니다.


function validateEmail(emailaddress){  
   var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;  
   if(!emailReg.test(emailaddress)) {  
        alert("Please enter valid email id");
   }       
}

<script type = "text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type = "text/javascript">
    function ValidateEmail(email) {
        var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
        return expr.test(email);
    };
    $("#btnValidate").live("click", function () {
        if (!ValidateEmail($("#txtEmail").val())) {
            alert("Invalid email address.");
        }
        else {
            alert("Valid email address.");
        }
    });
</script>
<input type = "text" id = "txtEmail" />
<input type = "button" id = "btnValidate" value = "Validate" />

여기에 착륙했습니다 .... 여기에 끝났습니다 : https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address

... 다음 정규식을 제공했습니다.

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/

... jQuery Validation 플러그인 readme에 대한 메모 덕분에 발견되었습니다 : https://github.com/jzaefferer/jquery-validation/blob/master/README.md#reporting-an-issue

따라서 @Fabian답변 의 업데이트 버전 은 다음과 같습니다.

function IsEmail(email) {
  var regex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
  return regex.test(email);
}

희망이 도움이


이것을 사용하십시오

if ($this.hasClass('tb-email')) {
    var email = $this.val();
    var txt = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!txt.test(email)) {
        e.preventDefault();
        $this.addClass('error');
    } else {
        $this.removeClass('error');
    }
}

일년 내내 중단적인 RegEx 경기보다 더 나은 유지 관리 솔루션 을 사용하려는 사람들을 위해 몇 줄의 코드를 작성했습니다. 바이트를 저장하려는 사람은 RegEx 변형을 고수하십시오. :)

이것은 다음을 제한합니다.

  • 문자열에 @가 없습니다.
  • 문자열에 점이 없음
  • @ 다음에 2 점 이상
  • 사용자 이름에 잘못된 문자 (@ 이전)
  • 문자열에서 2 @ 이상
  • 도메인의 잘못된 문자
  • 하위 도메인의 잘못된 문자
  • TLD의 나쁜 문자
  • TLD-주소

어쨌든 여전히 유출이 가능하므로 이것을 서버 측 유효성 검사 + 이메일 링크 확인과 결합하십시오.

여기 JSFiddle이 있습니다

 //validate email

var emailInput = $("#email").val(),
    emailParts = emailInput.split('@'),
    text = 'Enter a valid e-mail address!';

//at least one @, catches error
if (emailParts[1] == null || emailParts[1] == "" || emailParts[1] == undefined) { 

    yourErrorFunc(text);

} else {

    //split domain, subdomain and tld if existent
    var emailDomainParts = emailParts[1].split('.');

    //at least one . (dot), catches error
    if (emailDomainParts[1] == null || emailDomainParts[1] == "" || emailDomainParts[1] == undefined) { 

        yourErrorFunc(text); 

     } else {

        //more than 2 . (dots) in emailParts[1]
        if (!emailDomainParts[3] == null || !emailDomainParts[3] == "" || !emailDomainParts[3] == undefined) { 

            yourErrorFunc(text); 

        } else {

            //email user
            if (/[^a-z0-9!#$%&'*+-/=?^_`{|}~]/i.test(emailParts[0])) {

               yourErrorFunc(text);

            } else {

                //double @
                if (!emailParts[2] == null || !emailParts[2] == "" || !emailParts[2] == undefined) { 

                        yourErrorFunc(text); 

                } else {

                     //domain
                     if (/[^a-z0-9-]/i.test(emailDomainParts[0])) {

                         yourErrorFunc(text); 

                     } else {

                         //check for subdomain
                         if (emailDomainParts[2] == null || emailDomainParts[2] == "" || emailDomainParts[2] == undefined) { 

                             //TLD
                             if (/[^a-z]/i.test(emailDomainParts[1])) {

                                 yourErrorFunc(text);

                              } else {

                                 yourPassedFunc(); 

                              }

                        } else {

                             //subdomain
                             if (/[^a-z0-9-]/i.test(emailDomainParts[1])) {

                                 yourErrorFunc(text); 

                             } else {

                                  //TLD
                                  if (/[^a-z]/i.test(emailDomainParts[2])) {

                                      yourErrorFunc(text); 

                                  } else {

                                      yourPassedFunc();
}}}}}}}}}

checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );

참조 : JQUERY UI 웹 사이트


: 당신이 볼 수 jquery.validate.js을 프로젝트에 추가

이것을 다음과 같이 사용하십시오 :

<input id='email' name='email' class='required email'/>

버그는 Jquery Validation Validation Plugin에 있습니다. 변경하려면 @로만 유효성을 검사하십시오.

코드를 이것으로 변경하십시오

email: function( value, element ) {
    // From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29
    // Retrieved 2014-01-14
    // If you have a problem with this implementation, report a bug against the above spec
    // Or use custom methods to implement your own email validation
    return this.optional( element ) || /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test( value );
}

또 다른 간단하고 완전한 옵션 :

<input type="text" id="Email"/>
<div id="ClasSpan"></div>   
<input id="ValidMail" type="submit"  value="Valid"/>  


function IsEmail(email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
}

$("#ValidMail").click(function () {
    $('span', '#ClasSpan').empty().remove();
    if (IsEmail($("#Email").val())) {
        //aqui mi sentencia        
    }
    else {
        $('#ClasSpan').append('<span>Please enter a valid email</span>');
        $('#Email').keypress(function () {
            $('span', '#itemspan').empty().remove();
        });
    }
});

당신은 당신의 자신의 기능을 만들 수 있습니다

function emailValidate(email){
    var check = "" + email;
    if((check.search('@')>=0)&&(check.search(/\./)>=0))
        if(check.search('@')<check.split('@')[1].search(/\./)+check.search('@')) return true;
        else return false;
    else return false;
}

alert(emailValidate('your.email@yahoo.com'));

if($("input#email-address").getVerimailStatus() < 0) { 

(incorrect code)

}

if($("input#email-address").getVerimailStatus() == 'error') { 

(right code)

}

방금 만든 간단한 것, 내가 필요한 것을 수행합니다. 영숫자, 마침표, 밑줄 및 @로만 제한하십시오.

<input onKeyUp="testEmailChars(this);"><span id="a"></span>
function testEmailChars(el){
    var email = $(el).val();
    if ( /^[a-zA-Z0-9_@.-]+$/.test(email)==true ){
        $("#a").html("valid");
    } else {
        $("#a").html("not valid");
    }
}

다른 사람들의 도움으로 만든


이 정규 표현식은 abc@abc.com.com.com.com과 같은 중복 도메인 이름을 방지하며 abc@abc.co.in과 같은 도메인은 두 번만 허용합니다. 또한 123abc@abc.com과 같은 숫자의 스레 팅을 허용하지 않습니다.

 regexp: /^([a-zA-Z])+([a-zA-Z0-9_.+-])+\@(([a-zA-Z])+\.+?(com|co|in|org|net|edu|info|gov|vekomy))\.?(com|co|in|org|net|edu|info|gov)?$/, 

모든 최고 !!!!!


버튼 상태 처리를 통해 입력하는 동안 이메일을 확인하십시오.

$("#email").on("input", function(){
    var email = $("#email").val();
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    if (!filter.test(email)) {
      $(".invalid-email:empty").append("Invalid Email Address");
      $("#submit").attr("disabled", true);
    } else {
      $("#submit").attr("disabled", false);
      $(".invalid-email").empty();
    }
  });

jqvalidate 버전 1.11.0 에서이 코드를 가져 와서 버전 1.16.0에서 추가 방법으로 구현했습니다. 효과가있다

            jQuery.validator.addMethod("strictemail", function(value, element) {
                    var valid = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value);
                    return valid;
                }, "Escribe un correo v\u00e1lido"
            );

그리고 이메일 규칙에서

            'correo': {
                required: 'Por favor ingresa tu correo',
                email: 'Escribe un correo v\u00e1lido',
                strictemail:'Escribe un correo v\u00e1lido'
            }

jQuery Validation을 사용 하고 단일 HTML 행에서 이메일 및 이메일 유효성 검증 메시지를 유효성 검증 할 수 있습니다.type="email" required data-msg-email="Enter a valid email account!"

당신이 사용할 수있는 데이터 MSG-이메일 "유효한 이메일 주소를 입력하십시오."개인의 메시지를 배치하는 데 매개 변수를하거나이 매개 변수를 배치하지 않고 기본 메시지가 표시됩니다

전체 예 :

<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>
    <p>
      <label for="cemail">E-Mail (required)</label>
      <input id="cemail" type="email" name="email" required data-msg-email="Enter a valid email account!">
    </p>
    <p>
      <input class="submit" type="submit" value="Submit">
    </p>
  </fieldset>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation@1.17.0/dist/jquery.validate.js"></script>
<script>
$("#commentForm").validate();
</script>

이 질문은 첫눈에 보이는 것보다 대답하기가 더 어렵습니다. 이메일을 올바르게 처리하려면

전 세계에서 "모든 것을 다룰 정규식"을 찾고있는 많은 사람들이 있었지만 사실은 이메일 제공 업체가 많다는 것이 진실입니다.

뭐가 문제 야? "a_z%@gmail.com은 존재하지 않지만 다른 공급자"a__z@provider.com을 통해 이와 같은 주소가 존재할 수 있습니다.

왜? 다음 RFC에 따르면 https://en.wikipedia.org/wiki/Email_address#RFC_specification .

강의를 돕기 위해 발췌를하겠습니다.

The local-part of the email address may use any of these ASCII characters:

- uppercase and lowercase Latin letters A to Z and a to z;
- digits 0 to 9;
- special characters !#$%&'*+-/=?^_`{|}~;
- dot ., provided that it is not the first or last character unless quoted, and provided also that it does not appear consecutively unless quoted (e.g. John..Doe@example.com is not allowed but "John..Doe"@example.com is allowed);[6]
Note that some mail servers wildcard local parts, typically the characters following a plus and less often the characters following a minus, so fred+bah@domain and fred+foo@domain might end up in the same inbox as fred+@domain or even as fred@domain. This can be useful for tagging emails for sorting, see below, and for spam control. Braces { and } are also used in that fashion, although less often.
- space and "(),:;<>@[\] characters are allowed with restrictions (they are only allowed inside a quoted string, as described in the paragraph below, and in addition, a backslash or double-quote must be preceded by a backslash);
- comments are allowed with parentheses at either end of the local-part; e.g. john.smith(comment)@example.com and (comment)john.smith@example.com are both equivalent to john.smith@example.com.

따라서 다음과 같은 이메일 주소를 소유 할 수 있습니다.

A__z/J0hn.sm{it!}h_comment@example.com.co

이 주소를 시도하면 정규식의 전체 또는 주요 부분이 모두 인터넷에 게시됩니다. 그러나이 주소는 RFC 규칙을 따르므로 공정하게 유효합니다.

그 정규 표현식으로 확인 된 곳을 등록 할 수 없다는 것에 좌절감을 상상해보십시오!

실제로 이메일 주소를 확인할 수있는 유일한 사람은 이메일 주소 제공 업체입니다.

어떻게 처리해야합니까?

사용자가 거의 모든 경우에 유효하지 않은 전자 메일을 추가해도 문제가되지 않습니다. RFC 근처 에서 실행되는 HTML 5 입력 type = "email" 을 사용하면 실패 할 가능성이 거의 없습니다. HTML5 입력 유형 = "이메일"정보 : https://www.w3.org/TR/2012/WD-html-markup-20121011/input.email.html

예를 들어 다음은 RFC 유효한 이메일입니다.

"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com

그러나 html5 유효성 검사는 @ 앞에 텍스트에 "또는 () 문자가 포함되어서는 안된다는 것을 알려줍니다. 실제로는 올바르지 않습니다.

어쨌든, 전자 메일 주소를 수락하고 해당 전자 메일 주소로 전자 메일 메시지를 보내서 사용자가 유효성을 확인하기 위해 방문해야하는 코드 / 링크와 함께이 작업을 수행해야합니다.

이 작업을 수행하는 동안 사용자 입력 오류를 방지하기 위해 "이메일을 다시 입력하십시오"입력을하는 것이 좋습니다. 이것으로 충분하지 않은 경우 제목이 "현재 전자 우편입니까?"라는 제목으로 사전 제출 모달 창을 추가 한 다음 사용자가 h2 태그 안에 입력 한 메일을 추가하여 -메일을 입력 한 다음 "예, 제출"버튼을 클릭하십시오.

참고 URL : https://stackoverflow.com/questions/2507030/email-validation-using-jquery



반응형