Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regex question 3

Status
Not open for further replies.

richardko

Programmer
Jun 20, 2006
127
US
Hi I am trying to use javascript to find if a string contains only alphabets and no other character such as dot, backslash but getting nowhere.
I thought the carat negated the result but it still is not working.

function checkform()
{

var firstName = document.csupport.firstname2.value;
var fnamefilter = /([a-zA-Z])+[^.]/;

if ( fnamefilter.test(firstName))
{
alert("Success");
}else{
alert('Please enter correct email address');
}
}


 
Here's an example:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript">

function regex(str) {
   if (/^[A-Za-z]+$/.test(str)) {
      alert(str + " contains only alpha characters");
   }
   else {
      alert(str + " contains non alpha characters");
   }
}

var a = "abcdefghijklmnopqrstuvwxyz";
var b = "1234abcdef";
var c = "asdfjkl;";

regex(a);
regex(b);
regex(c);

</script>
<style type="text/css"></style>
</head>
<body>
</body>
</html>

-kaht

[small](All puppies have now found loving homes, thanks for all who showed interest)[/small]
 
would it not be more like this?

Code:
function checkform()
{
        
        var firstName = document.csupport.firstname2.value;                
        var fnamefilter = /(^[a-zA-Z])*$/;
       
        if ( firstName.search(fnamefilter) == -1)
        {
                alert("Please enter correct email addres");            
        }else{
                alert('success');
        }
}
although, of course, an alpha only regex will not validate an email address!

afaik the carat asserts the start of a string.
 
afaik the carat asserts the start of a string.

When specifying a collection (via []) in a regexp, putting ^ at the beginning of the collection (as the OP did above) negates the collection.

For example:
Code:
/[^abc]/
matches any character that is not a, b, or c

-kaht

[small](All puppies have now found loving homes, thanks for all who showed interest)[/small]
 
richardko, did you find any of these solutions helpful?

-kaht

[small](All puppies have now found loving homes, thanks for all who showed interest)[/small]
 
oops,
sorry for late replies. All the inputs were helpful. It seems everytime I use regex I learn something new and definitely the posts were helpful.
ro
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top