title: Checking input string for the invalid character(s) using regex
body: <p>I have the following code snippet in which I am checking a name for invalid characters and false is returned as soon as user enters invalid character (allowed characters are defined in regex).</p>
  
  <p>Issue is: This works fine as long as user enters invalid character at the end of the line but if user enters any invalid character in between the ItemName i.e. moving the cursor back somewhere in the middle of the ItemName then he is allowed to write invalid character i.e. true is returned while false should have been returned.</p>
  
  <p>What mistake am I doing in defining the regex? Or any other mistake? Thanks</p>
  
  <pre><code>bool validName = true;
  Regex regex = new Regex(@"[a-zA-Z0-9_-]+$");
  if (regex.IsMatch(ItemName, 0) == false) validName = false;
  if (!validName)
  {
      return false;
  }
  else
  {
      return true;
  }
  </code></pre>
  
  <p>Please let me know if anything is not clear.</p>
  
  <p>Edit: I changed my regex from (@"[a-zA-Z0-9_-]+$") to (@"^[a-zA-Z0-9_-]*$") and it worked. Is there any obvious mistake I am doing or this is the correct solution? </p>