Someone said I could ask this again with these new updates I need.
I need a code that will force the following input for 3 different inputs, 2 with the same patterns, the other an email.
Display Name & Real Name:
- Force first character to be a letter
- Capitalize first letter of all words (even single characters)
- Force the rest of the letters in words lowercase
- Allow single spaces (also prevent consecutive spaces)
- Prevent all special characters
- Allow all numbers
E-mail:
- prevent all spaces
- force all letters to be small
- prevent multiple @’s
- prevent consecutive .’s in a row (allow multiple .’s but not in a row)
- prevent @ and . beside each other (both ways: @. and .@)
function handleNameFieldKeypress(target, evt) {
console.log('handleNameFieldKeypress ... target ...', target);
const char = String.fromCharCode(evt.which);
const { selectionStart } = target;
const isNotValid = (selectionStart === 0 && (
evt.code === 'Space' ||
!/^[a-zA-Z]$/.test(char)
)) || (
char === ' ' &&
target.value.charAt(selectionStart - 1) === ' '
);
if (isNotValid) {
evt.preventDefault();
}
}
function handleEmailFieldKeypress(target, evt) {
console.log('handleEmailFieldKeypress ... target ...', target);
const { selectionStart } = target;
const isNotValid =
(selectionStart === 0 && evt.code === 'Space') || (
String.fromCharCode(evt.which) === '@' &&
target.value.charAt(selectionStart - 1) === '@' ) || (
String.fromCharCode(evt.which) === '@' &&
target.value.charAt(selectionStart - 1) === '.' ) || (
String.fromCharCode(evt.which) === '.' &&
target.value.charAt(selectionStart - 1) === '@' ) || (
String.fromCharCode(evt.which) === '.' &&
target.value.charAt(selectionStart - 1) === '.'
);
if (isNotValid) {
evt.preventDefault();
return;
}
const key = evt.keyCode || evt.charCode || evt.which;
return (key !== 32) && key;
}
function handleInputFieldKeypress(evt) {
const { target } = evt;
let result;
if (target.matches('input[name="real_name"], input[name="display_name"]')) {
result = handleNameFieldKeypress(target, evt);
} else if (target.matches('input[name="email"]')) {
result = handleEmailFieldKeypress(target, evt);
}
return result;
}
document
.addEventListener('DOMContentLoaded', () => {
document
.querySelector('form')
.addEventListener('keypress', handleInputFieldKeypress);
});
<input type="text" name="email" placeholder="E-mail" id="email">
<input type="text" name="real_name" placeholder="Real Name" id="real_name">
<input type="text" name="display_name" placeholder="Display Name" id="display_name">
Your help would be greatly appreciated!