user9133748
user9133748

Reputation: 11

Validate Users Input so that users can only enter Alphabets

I am trying to validate the user input so that user can only enter alphabets. When I implement this, I can not type any characters at all or numbers, basically the input does not work. Any ideas please?

function validateName(){
  if( /^[a-zA-Z ]{2,30}$/.exec(name)){
    return true;
  }
  return false;
}
<input type="text" onkeypress="return validateName()" placeholder="First Name" name="first_name" required> <!-- Only alphabets can be entered -->
<input type="text" onkeypress="return validateName()" placeholder="Last Name" name="last_name" required> <!-- Only alphabets can be entered -->

Upvotes: 1

Views: 97

Answers (2)

Emre Kabaoglu
Emre Kabaoglu

Reputation: 13146

You should pass the entered key to event function and fix the regex.

function validateName(event) {
if (/^[A-z]+$/.exec(event.key)) {
	return true;
}
return false;
}
<input type="text" onkeypress="return validateName(event) " placeholder="First Name" name="first_name" required/> <!-- Only alphabets can be entered -->
<input type="text" onkeypress="return validateName(event) " placeholder="Last Name" name="last_name" required/>   <!-- Only alphabets can be entered --> 

Upvotes: 1

R.F. Nelson
R.F. Nelson

Reputation: 2312

You might want to look at this post, which is trying to accomplish the same thing: detect numbers or letters with jquery/javascript?

Upvotes: 0

Related Questions