menu

Questions & Answers

Why HTML5 input type email doesn't allow empty space?

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>

Comments:
2023-01-17 00:47:02
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. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… You could even trim the value in the input field directly.
Answers(1) :

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...

Comments:
2023-01-17 00:47:02
I think second option is much easier and cleaner approach. Thanks for your help.
2023-01-17 00:47:02
@espresso_coffee I'd agree. But only you know what's best for your situation.
2023-01-17 00:47:02
"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?, Email address
2023-01-17 00:47:02
@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.