首页 > 解决方案 > 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>

标签: javascripthtmlhtml-email

解决方案


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


推荐阅读