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