English alphabets input only?

Is it possible to restrict an input to the a-z keyboard only? We had a legit user fill out a form on our website today in Bulgarian. Thanks Google translate.

Will a regex expression work?

Any Regex experts out there? Does this look right?

^[A-Za-z0-9!@#$%^&*()\-_=+{}\[\]:;"'<>,.?/\\|`~\s]+$

Source: ChatGPT

Hi Brad, I would do it this way:

 /^[a-z]$/i

If u wanna do it with javascript:

const inputElement = document.querySelector('input');
inputElement.addEventListener('keypress', function(event) {
  const regex = /^[a-z]$/i;
  if (!regex.test(event.key)) {
    event.preventDefault();
  }
});

Thanks Max,

I need to allow for the whole keyboard (spaces included) to be used though, not just the letters. Also, how would I show a validation message using javascript?

Oh sorry, then the regex should be:

/^[a-zA-Z0-9 !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/;

You can modify the event listener to check for valid input and use the setCustomValidity method for invalid cases.

So if im not wrong the js should be:

const inputElement = document.querySelector('input');

inputElement.addEventListener('input', function(event) {
  const regex = /^[a-zA-Z0-9 !@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/;
  if (!regex.test(inputElement.value)) {
    inputElement.setCustomValidity("Invalid input: Only keyboard characters are allowed.");
  } else {
    inputElement.setCustomValidity("");
  }
  inputElement.reportValidity();
});

I checked with chatgpt and it says the code is good, but im using my phone now so i cant test it

You can use Wappler’s built-in validation options (Pattern) - and enter Max’s regex there (without the leading and trailing slashes):

image

2 Likes