Patrick Kwinten
Patrick Kwinten

Reputation: 2048

onkeypress allowing only allowed domains while writing email address

For my xpages/jsf application I have setup for an xe:input control the following validation:

<xp:this.validators>
<xp:validateConstraint
    regex="${application.regex_email}"
    message="please follow the rules">
</xp:validateConstraint>
<xp:validateRequired
    message="follow the rules">
</xp:validateRequired>
</xp:this.validators>

The regular expression I use:

regex_email=^([\w-]+(?:\.[\w-]+)*)@(acme\.org|acme\.com)

(so I allow only email addresses from acme.org and acme.com domains, case sensitive).

This works fine when sending the data to the server but I want to apply something similar to validation on the client-side.

I guess in the onkeyup event a similar check occurs so only the allowed domains in lowercase characters are allowed, so as soon the user would write 'john.doe@A' it would be allowed BUT transformed to lowercase (john.doe@a) and when writing john.doe@s it would starts alerting the user that the domain is not acceptable.

But I do not know how. Can anyone explain how to?

Upvotes: 0

Views: 65

Answers (2)

mplungjan
mplungjan

Reputation: 178375

This will validate while typing

const emailInput = document.getElementById('email');
const errorMessage = document.getElementById('error-message');

// Allowed domains
const allowedDomains = ['acme.org', 'acme.com'];

emailInput.addEventListener('input', () => {
  const emailValue = emailInput.value;
  const atIndex = emailValue.indexOf('@');

  let isAllowed = true;

  // Check if the "@" symbol is present and if so, start validating the domain after it
  if (atIndex > -1) {
    const domainPart = emailValue.slice(atIndex + 1);
    // Check if any of the allowed domains starts with the (partially entered) domain
    isAllowed = allowedDomains.some(domain => domain.startsWith(domainPart));
    // Show error if the domain part does not match any allowed domain
    errorMessage.hidden = isAllowed || domainPart.length === 0;
  } else {
    // Hide error if no "@" symbol is present yet
    errorMessage.hidden = true;
  }
});
<input type="email" id="email" placeholder="Enter your email" />
<div id="error-message" style="color: red;" hidden>Invalid email domain. Must be @acme.org or @acme.com</div>

Upvotes: 0

ControlAltDel
ControlAltDel

Reputation: 35096

Use the pattern attribute of input. It makes it so the form cannot be submitted until the regex in this field matches (see my example below).

This is better than a key listener, because even if you try to block certain key strokes, the user can still copy/paste an email address in (unless you block this too, which... do you really want to do this to people?)

Note: This attribute was first introducted in the HTML 5 specification.

Form matches "foo" and a digit
<form>
<input pattern="foo\d">
<input type="submit">
</form>

Upvotes: 0

Related Questions