-1

I have created a regex function and called it when the data is being saved.

public static bool CheckSpecialCharacter(string value)
{
   System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"[~`!@#$%^*()=|\{}';.,<>]");
   if (regex.IsMatch(value))
   {
      return false;
   }
   else
   {
      return true;
   }
}

Used here:

if (ClassName.CheckSpecialCharacter(txt_ExpName1.Text)==false)
{
    lblErrMsg.Text = "Special characters not allowed";
    return;
}

Now instead of writing "Special characters not allowed", I want to attach the 1st special character that was entered in the textbox, so if @ was entered, the message should be read as "Special character @ not allowed"

Is it possible to do this? please help.Thanks.

ZwoRmi
  • 1,093
  • 11
  • 30
Sumedha Vangury
  • 643
  • 2
  • 17
  • 43

3 Answers3

1

Try following code.

public static string CheckSpecialCharacter(string value)
{
   System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"[~`!@#$%^*()=|\{}';.,<>]");
   var match = regex.Match(value);
   if (match.Success)
   {
      return match.Value;
   }
   else
   {
      return string.empty;
   }
}

usage:

var value = ClassName.CheckSpecialCharacter(txt_ExpName1.Text);
if (!string.IsNullOrEmpty(value ))
{
    lblErrMsg.Text = value + " Special characters not allowed";
    return;
}

OR you can do it by returning bool and adding one out parameter in the function, but i will not suggest that.. check this link

EDIT - To do the same thing in Javascript

function CheckSpecialCharacter(value)
{
  var res = value.match(/[~`!@#$%^*()=|\{}';.,<>]/g);
  return res == null ? "" : res[0];
}

usage:

var value = CheckSpecialCharacter(document.getElementById("txt_ExpName1").value);

if(value != "")
{
   document.getElementById("lblErrMsg").innerHTML = value + " Special characters not allowed";
}
Community
  • 1
  • 1
K D
  • 5,889
  • 1
  • 23
  • 35
0

Try this:

public static bool CheckSpecialCharacter(string value, out string character)
{
    var regex = new System.Text.RegularExpressions.Regex(@"[~`!@#$%^*()=|\{}';.,<>]");
    var match = regex.Match(value);
    character = regex.Match(value).Value;
    return match.Length == 0;
}

and then

string character;
if (ClassName.CheckSpecialCharacter(txt_ExpName1.Text, out character) == false)
{
    lblErrMsg.Text = character + " Special characters not allowed";
    return;
}
Damian
  • 2,752
  • 1
  • 29
  • 28
0

You can just use the Matches(string) function from Regex to get the matches then check the first element like this :

var regex = new Regex(@"[~`!@#$%^*()=|\{}';.,<>]");
var matches = regex.Matches("This contains # two b@d characters");
if (matches.Count > 0)
{
    var firstBadCharacter = matches[0];
}

Then you can wrap the result of your check in an Exception :

throw new ArgumentException("Special character '" + firstBadCharacter + "' not allowed.");
Foxtrot
  • 607
  • 4
  • 10