0

I'm having real trouble with checking that an email is in avalid format before posting to a database. I can't figure out how to write the condition so that the form sends if it is valid but not if it is invalid.

Really appreciate any pointers. Thanks

jQuery

          // on post comment click 
            $('#bt-add-com').click(function(){
                var theCom = $('.the-new-com');
                var theName = $('#name-com');
                var theMail = $('#mail-com');

    //Check inputs are not empty
                if( !theCom.val()){ 
                    swal("Error", "You need to write a comment!", "error");


                 if( !theName.val()){ 
                    swal("Error", "You need to write a name!", "error");

    //Check email is valid

    function validateEmail(theMail){
        var emailReg = 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);
        var valid = emailReg.test(theMail);

        if(!valid) {
            return false;
        } else {
            return true;
        }
    }

    if(validateEmail(theMail)){
         //E
//EMAIL IS VALID, NOW SEND
    } else {
         alert("Email is not correct format return false.");
//EMAIL IS INVALID DO NOT SEND THE
    }

      }
      }else{ 


                    $.ajax({
                        type: "POST",
                        url: "comments/ajax/add-comment2.php",
                        data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&name='+theName.val()+'&email='+theMail.val()+'&comment='+theCom.val(),
                        success: function(html){
                            theCom.val('');
                            theMail.val('');
                            theName.val('');

                                $('.new-com-bt').fadeIn();
                                $('.response').fadeIn().append(html); 

    $('.new-com-cnt').hide('slow');//fade out form
    swal("Success", "Your comment is posted", "success");


                        }  
                    });
                }
            });

        });
          });
JulianJ
  • 1,259
  • 3
  • 22
  • 52
  • I assume that you also check it on server side? Client side validation is only for user experience. You can't ever rely on it. – Ivar Jan 27 '18 at 14:02
  • Possible duplicate of [How can you validate an email address in JavaScript?](https://stackoverflow.com/questions/46155/how-can-you-validate-an-email-address-in-javascript) – Ivar Jan 27 '18 at 14:02
  • @Ivar yes, using php to protect against injection. – JulianJ Jan 27 '18 at 14:03

0 Answers0