drlq92444
2015-12-12 07:37
浏览 54

验证表单的textarea - jQuery

I am trying to develope a plugin for an application that let the users invite their friends to use the application by just sending an email. Juts like Dropbox does to let the users invite friends and receive extra space.

I am trying to validate the only field I have in the form (textarea) with JQuery (I am new to JQuery) before submiting it and be handled by php.

This textarea will contain email addresses, separated by commas if more than one. Not even sure if textarea is the best to use for what I am trying to accomplish. Anyway here is my form code:

<form id="colleagues" action="email-sent.php" method="POST">
    <input type="hidden" name="user" value="user" />
    <textarea id="emails" name="emails" value="emails" placeholder="Example: john@mail.com, thiffany@mail.com, scott@mail.com..."></textarea>
    </br><span class="error_message"></span>
    <!-- Submit Button -->
     <div id="collegues_submit">              
        <button type="submit">Submit</button>
     </div>
</form>

Here is what I tried in Jquery with no success:

//handle error 
    $(function() {
          $("#error_message").hide();
          var error_emails = false;

          $("#emails").focusout(function() {
            check_email();
          });

        function check_email() {
          if(your_string.indexOf('@') != -1) {
            $("#error_message").hide();
          } else {
            $("#error_message").html("Invalid email form.Example:john@mail.com, thiffany@mail.com, scott@mail.com...");
            $("#error_message").show();
            error_emails = true;
            }
          }
          
          $("#colleagues").submit(function() {
            error_message = false;
            
            check_email();
            
            if(error_message == false) {
              return true;
            } else {
              return false;
            }
    });

I hope the question was clear enough, if you need more info please let me know.

Many thanks in advance for all your help and advises.

</div>
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • doumengwei0138 2015-12-12 08:02
    已采纳

    I would use, as I commented above, append() or prepend() and just add fields. As mentioned in another post, client side use jQuery validation, but you should for sure validate server-side using a loop and filter_var($email, FILTER_VALIDATE_EMAIL). Here is a really basic example of the prepend():

    <form id="colleagues" action="" method="POST">
        <input type="hidden" name="user" value="user" />
        <input name="emails[]" id="starter" placeholder="Email address" />
        <div id="addEmail">+</div>
        </br><span class="error_message"></span>
        <!-- Submit Button -->
         <div id="collegues_submit">                
            <button type="submit">Submit</button>
         </div>
    </form>
    <script>
    $(document).ready(function() {
        $("#addEmail").click(function() {
            $("#colleagues").prepend('<input name="emails[]" placeholder="Email address" />');
        });
    });
    </script>
    
    已采纳该答案
    打赏 评论
  • doulang6695 2015-12-12 07:43

    Your code might look correct, but you are using bad technique. My advice is to use jquery validation plugin that would handle textarea validation.for you. Also notice. There might be many solutions for this problem, but you should stick with simple one. And the first problem i see stright away is: button tag doesnt have type attribute. You are changing #error_message html, not text. Etc...

    打赏 评论
  • douti6740 2015-12-12 07:50

    Few errors as I noted down:

    1. The code snippet posted here has missing braces }); at the end.
    2. Also, what is your_string variable in the function check_email.
    3. Also, error_message is assigned false always so the submit method will return true always.

    Fixing this issues should help you.

    打赏 评论
  • dongwei6700 2015-12-12 07:52
        var array = str.split(/,\s*/);
        array.every(function(){
        if(!validateEmail(curr)){
        // email is not valid!
    return false;
        }
        })
    

    // Code from the famous Email validation

    function validateEmail(email) {
        var re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
    }
    
    打赏 评论
  • dongye9991 2015-12-12 08:20

    Hi please use below js code,

      $('#emails').focusout(function(e) {
      var email_list = $('#emails').val();
      var email_list_array = new Array();
      email_list_array = email_list.split(",");
      var invalid_email_list=' ';
      $.each(email_list_array, function( index, value ) {
    
       if(!validEmail(value))
       {
         invalid_email_list=invalid_email_list+' '+value+',';
       }
      });
          console.log(invalid_email_list+' is not correct format.');
         alert(invalid_email_list+' is not correct format.');
     })
    
     function validEmail(v) {
    var r = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
    return (v.match(r) == null) ? false : true;
    }
    

    If you need to check more REGEX just do it validEmail() function. I hope this will help to sort out.

    thank you

    打赏 评论

相关推荐 更多相似问题