2 Replies - 3895 Views - Last Post: 09 December 2012 - 06:04 AM

#1 tanuja90  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 04-December 12

Regular expression to check if a string contains only alphabets

Posted 09 December 2012 - 04:27 AM

I need to validate if a string contains only alphabets (space allowed in between). Here's my code. But, it doesn't allow spaces. Please let me know how will change the code to the desired result. Any help will be highly appreciated

function checkNames(name){
	var regex1 = /\d/;
	var regex2 = /[^\w\*]/;
	if(regex1.test(name)){
		//Contain numbers
		return false;
	}
	else{
		//No numbers
		if(regex2.test(name)){
			//contain special characters
			return false;
		}
		else{
			//no special characters
			return true;
		}
	}
}




Is This A Good Question/Topic? 0
  • +

Replies To: Regular expression to check if a string contains only alphabets

#2 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3730
  • View blog
  • Posts: 6,017
  • Joined: 08-June 10

Re: Regular expression to check if a string contains only alphabets

Posted 09 December 2012 - 04:52 AM

It would be far simpler to test what chars are supposed to be in there, rather than which chars are not supposed to be there. If you only want alphabet characters and spaces, then just test for those:
function checkNames(name){
	return /^[a-z ]*$/i.test(name);
}


Was This Post Helpful? 1
  • +
  • -

#3 tanuja90  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 04-December 12

Re: Regular expression to check if a string contains only alphabets

Posted 09 December 2012 - 06:04 AM

Thank you so much. It worked. Actually, I'm not so familiar with regular expressions. That's why I made things very complex. Thank you again. :bigsmile:/>
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1