views:

132

answers:

5

I have this code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>sss</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />


<script type='text/javascript'>
function isAlphabet(obj){

    var alphaExp = /[^a-z0-9_-]+/;
    if(!obj.value.match(alphaExp)){
     return true;
    }
    else{
     alert('the bad symbols');
     obj.focus();
     return false;
    }
}
</script>

</head>
<body>

    <form action="/">
     <input type='text' id='letters' onblur="isAlphabet(this)"/>
    </form>

</body>
</html>


And I want to show an Alert() displaying only those characters for which validation fails.

For example :

If an input contains symbols like " #abc " , the Alert Message should show only "#". How can this be done?

A: 

You could matchall on regex which contains all the prohibited symbols (like your alphaExp), and then concatenate the matches.

EFraim
+2  A: 

Here's a simple way to do it... it's not be the most efficient though:

function isAlphabet(obj)
{
    var val = obj.value;
    var alphaExp = /[^a-z0-9_-]+/;

    var valid = true;
    var badchars = "";

    for( a = 0; a < val.length; a++ )
    {
     if(val[a].match(alphaExp))
     {
      badchars += "," + val[a];
      valid = false;
     }
    }

    if( !valid )
    {
     alert("The following characters are not allowed: " + badchars.substr(1));
     obj.focus();
    }

    return valid;
}
Kane Wallmann
That doesn't work in Internet Explorer earlier than version 8. You have to use val.charAt(a) or val.substr(a,1) instead of val[a].
Guffa
+1  A: 

In this case, you are matching characters that do not fall into the supplied ranges. Therefore, you can put the matched text into a backreference and use that.

Alternatively, you can construct a Regexp object and use it's lastMatch property.

Cerebrus
A: 

if you use the g modifier, you can get .match() to return you an array of matches (invalid chars in your case) then you can just display them.

see "String.match(pattern)" about 1/3 down this page: http://evolt.org/regexp_in_javascript

var str = "Watch out for the rock!".match(/r?or?/g)

str then contains ["o","or","ro"]

Andrew Bullock
+2  A: 

Use a regular expression which matches the allowed characters to get a string where those are removed. If the string contains anything, the validation fails:

function isAlphabet(obj) {
   var alphaExp = /[a-z0-9_-]+/g;
   var illegal = obj.value.replace(alphaExp, '');
   if (illegal.length){
      alert('Input contains the characters '+illegal+' which are not allowed.');
      obj.focus();
      return false;
   } else {
      return true;
   }
}
Guffa