0

I am trying to validate an email address when the submit email button is pressed.

I tried adding JQuery validation to no avail. I was wondering how I could add an "if" statement that will just check and inform the user, that it is not a valid email in the same label that states it is sending an email.

$('#Submit').on("click", function () {
  result = '<label style="color:white;">Sending message ...</label>';
  $("#sendSuccess").html(result);

  var email = $("#email").val(); 
  var body = "From: " + name + "<br />  Email: " + email + "<br /> Message: " + message;

  $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "EmailService.asmx/SendMail",
    data: '{ body: "' + body + '", subject: "' + subject + '"}',
    dataType: "json",
    async: true,

    success: function (data, status, xhr) {
      //alert('success');
      result = '<label style="color:green;">The message has been sent!</label>';
      $("#sendSuccess").html(result);
    },
    error: function (data, status, xhr) {
      //alert('fail');
      result = '<label style="color:red;">The message has failed to send!</label>';
      $("#sendSuccess").html(result);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <div>
    <input id="email" type="text" name="email"  class="form-control" />
  </div>
  <div>
    <button type="submit" id="Submit" class="form-control">Click</button>
      </div>
    </html>
Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49
Steven
  • 13
  • 3
  • At the beginning of the function, validate the email using a regular expression for emails (Google about it). If the validation is successful, proceed with the rest of the function. Otherwise, set the label you want and exit the function. – Vicente Olivert Riera Aug 31 '16 at 07:34
  • Would also recommend including the email field and submit button inside a `
    ` and then using `$('#myForm').on('submit', function() { ... });` instead of `$('#Submit').on('click')`. This way, if the user presses return, this will also trigger the submit functionality.
    – Steve Harrison Aug 31 '16 at 07:47
  • Note you would also have to do an `event.preventDefault()` if you used the above. Might be easier leaving it as it is for the time being. – Steve Harrison Aug 31 '16 at 08:01

1 Answers1

0

You can do something like this:

<html>
<div>
  <input id="email" type="text" name="email"  class="form-control" />
</div>
<div>
  <button type="submit" id="Submit" class="form-control">
</div>
</html>

<script>
    function isValidEmail(email) {
      return /^[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])?)*$/i.test(email);
    }

    $('#Submit').on("click", function () {
        var email = $('#email').val();

        if (isValidEmail(email)) {
            result = '<label style="color:white;">Sending message ...</label>';
            $("#sendSuccess").html(result);

            var body = "From: " + name + "<br />  Email: " + email + "<br /> Message: " + message;

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "EmailService.asmx/SendMail",
                data: '{ body: "' + body + '", subject: "' + subject + '"}',
                dataType: "json",
                async: true,

                success: function (data, status, xhr) {
                    //alert('success');
                    result = '<label style="color:green;">The message has been sent!</label>';
                    $("#sendSuccess").html(result);
                },
                error: function (data, status, xhr) {
                    //alert('fail');
                    result = '<label style="color:red;">The message has failed to send!</label>';
                    $("#sendSuccess").html(result);
                }
            });


        } else {
            $('#sendSuccess').html('<label style="color:white;">Please enter a valid email address</label>');
        }
    });
<script/>

Keep in mind that this will validate most emails, but may reject some really weird email addresses that are technically valid. You can read more here and also at the StackOverflow answer others posted in the comments.

If you need to validate more fields though, it might be worth giving jQuery validation another shot... have used it before and definitely helps if you're doing a lot of generic form validation.

Community
  • 1
  • 1
Steve Harrison
  • 121,227
  • 16
  • 87
  • 72