patel
patel

Reputation: 635

How do I restrict a string to not allow numbers or special characters?

I have textbox called goalName. In goalName I want to disallow special characters and numbers. I am currently trying the following:

 var goalNameValidation = /^[_\W\s]*$/;
 if (goalName == "" || goalNameValidation.test(goalName) == true) {
     //Give Error 
     error = true;
 }

This only limits special characters, and not numbers. How would I go about restricting both?

I can use jQuery for this solution if that is helpful, however vanilla JavaScript would suffice.

Upvotes: 0

Views: 99

Answers (2)

mbomb007
mbomb007

Reputation: 4251

It is probably easier (and more intuitive) to write a regex that matches what you WANT to allow.

var goalNameValidation = /^[A-Za-z]+$/;
if (goalName == "" || goalNameValidation.test(goalName) == false) {
    //Give Error 
    error = true;
}

This way, you can look at it, and see more easily what characters are allowed/not allowed.

Upvotes: 1

Barmar
Barmar

Reputation: 781096

Change the regexp to:

var goalNameValidation = /^[^a-z]*$/i;

Upvotes: 0

Related Questions