input should reject non-alphabetical input reacj js

How to reject non-alphabetical input in JavaScript

As a web developer, I know the importance of validating user input to ensure that the data entered is accurate and secure. One common validation is to reject non-alphabetical input, which can be achieved through JavaScript.

Method 1: Using Regular Expressions

One way to validate input is by using regular expressions, also known as regex. Here's an example code snippet to reject non-alphabetical input:


let input = document.getElementById("myInput").value;
let regex = /^[a-zA-Z]+$/; // regex pattern that matches only alphabetical characters
if (!regex.test(input)) {
  alert("Please enter only alphabetical characters.");
}
  • document.getElementById("myInput").value retrieves the value of the input field with the ID "myInput".
  • /^[a-zA-Z]+$/ is a regex pattern that matches one or more alphabetical characters (uppercase or lowercase), and the ^ and $ symbols ensure that it matches the entire string.
  • regex.test(input) checks whether the input matches the regex pattern.
  • If the input doesn't match the pattern, an alert message is displayed.

Method 2: Using ASCII Codes

Another way to validate input is by using ASCII codes, which represent characters in a numerical format. Here's an example code snippet to reject non-alphabetical input:


let input = document.getElementById("myInput").value;
for (let i = 0; i < input.length; i++) {
  let charCode = input.charCodeAt(i);
  if ((charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)) {
    alert("Please enter only alphabetical characters.");
    break;
  }
}
  • The for loop iterates through each character in the input string.
  • input.charCodeAt(i) retrieves the ASCII code of the current character.
  • The if statement checks whether the ASCII code is outside the range of uppercase or lowercase alphabetical characters.
  • If a non-alphabetical character is found, an alert message is displayed and the loop is terminated using break.

Both of these methods work effectively to reject non-alphabetical input in JavaScript. It's important to choose a validation method that suits your needs and implement it consistently throughout your code to ensure data accuracy and security.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe