2

I use input type=email in my application. Prior to that in the old system developers user input type=text. Recently I was asked to fix the 'issue' in my code. The problem was reported by user when entering email address in the input field, accidentally empty space was entered on the end. Then user tried to Save the form, and error message was displayed under the email field This field is mistyped. I'm wondering if this is the way type=email should work and prevent empty space in the email address fields?

I tested this problem in Chrome and empty space will not be detected, but in Firefox will be and error message will show up.

$("#save").on("click", function() {
  console.log(verifyFields('my-form'));
  if (verifyFields('my-form')) {
    alert('Saved!');
  }
});

function verifyFields(containerID, includeInvisible) {
  includeInvisible = includeInvisible || false;
  let isValid = true;
  const hdlMap = {
    //'valueMissing': "This field is required",
    //'patternMismatch': "This field is invalid",
    'tooLong': "This field is too long",
    'rangeOverflow': "This field is greater than allowed maximum",
    'rangeUnderflow': "This field is less than allowed minimum",
    'typeMismatch': "This field is mistyped"
  };

  const arrV = Object.keys(hdlMap);
  const invalidInputs = [];

  $("#" + containerID).find("input,textarea,select").each(function() {
    var curItem$ = $(this);
    var errMsg = [];
    var dispfld = curItem$.data("dispfld");
    var label = curItem$.data("label");

    if (includeInvisible || curItem$.is(":visible")) {
      if (curItem$[0].validity.valid) {
        curItem$.removeClass("is-invalid");
        return;
      }

      if (curItem$[0].validity['valueMissing']) {
        var reqMsg = label ? label + " field is required" : "This field is required";
        errMsg.push(reqMsg);
      }

      if (curItem$[0].validity['customError'] && dispfld) {
        errMsg.push(dispfld);
      }

      if (curItem$[0].validity['patternMismatch'] && dispfld) {
        errMsg.push(dispfld);
      }

      arrV.forEach(function(prop) {
        if (curItem$[0].validity[prop]) {
          errMsg.push(hdlMap[prop]);
        }
      });

      if (errMsg.length) {
        if (!curItem$.next().is(".invalid-feedback")) {
          curItem$.after('<div class="invalid-feedback"></div>');
        }
        curItem$.addClass("is-invalid").next().text(errMsg.join(' and '));
        invalidInputs.push(curItem$);
        isValid = false;
      } else {
        curItem$.removeClass("is-invalid");
      }
    }
  });

  if (invalidInputs.length) {
    invalidInputs[0].focus();
  }

  return isValid;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="my-form" id="my-form">
  <input type="email" name="user-email" id="user-email" required>
  <button type="button" id="save">Save</button>
</form>
Rubén
  • 34,714
  • 9
  • 70
  • 166
espresso_coffee
  • 5,980
  • 11
  • 83
  • 193
  • [What characters are allowed in an email address?](https://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-an-email-address) – Andreas Jan 30 '20 at 16:07
  • Well, if Firefox and Chrome behave differently, then regardless of any standard, if you want to support both browsers, you'll have to handle any differences yourself. You could, for example, trim the string before saving. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim You could even trim the value in the input field directly. – Will Jan 30 '20 at 16:08

1 Answers1

5

a space isn't a valid character for an input type="email" because we can't have email addresses with spaces in them (A).

So in this case you have an unfortunate scenario where the space isn't in the middle of the email address, but at the beginning or end. But if you look at the validation that the browser follows for this input type, it still won't be allowed.

You have two options:

  1. Set it back to input type="text", but set the same validation pattern that applies for emails: <input type="text" pattern="/^[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])?)*$" /> and then modify that regex to allow for ending spaces (though you need to check on the back-end to make sure it will allow them, or otherwise you need to do a .trim() to remove those surrounding spaces.

  2. Do a .trim() on your input after the user exits the input; removing whitespaces at the start or end.

(A) According to this answer:

space and "(),:;<>@[] characters are allowed with restrictions (they are only allowed inside a quoted string...

paceaux
  • 1,762
  • 1
  • 16
  • 24
  • 1
    I think second option is much easier and cleaner approach. Thanks for your help. – espresso_coffee Jan 30 '20 at 16:14
  • 1
    @espresso_coffee I'd agree. But only you know what's best for your situation. – paceaux Jan 30 '20 at 16:16
  • _"a space isn't a valid character for an input type="email" because we can't have email addresses with spaces in them."_ - That's not true -> [What characters are allowed in an email address?](https://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-an-email-address), [Email address](https://en.wikipedia.org/wiki/Email_address) – Andreas Jan 30 '20 at 16:16
  • @Andreas thank you, I updated my answer. The space is allowed _with restrictions_. Based on how that reads, I don't think I was totally off base. – paceaux Jan 30 '20 at 16:23