1

I have developed a mobile application where the back end of it is .net framework. I need to validate the data coming to the backend are presence of dangerous characters such as

<>&%;={}()

If those type of characters present I need to terminate the request and send an error message

Udara Abeythilake
  • 1,150
  • 1
  • 17
  • 29
  • Is it a requirement to use Regex to solve the problem? – Lars Kristensen Feb 10 '20 at 08:23
  • 7
    In what sense are these "dangerous characters"? – Tom W Feb 10 '20 at 08:28
  • Put another way, what is the set of _valid_ characters, and why is that the set? – ClickRick Feb 10 '20 at 08:48
  • @Udara, I guess you should add the purpose of restricting those characters to your question. If you'd like to prevent having HTML in your string, that's a different story, for JS it's another, for storing files, for SQL, they are completely different. Knowing the purpose would make it easier for us to help you. – Just Shadow Feb 10 '20 at 09:10
  • 1
    Why do you consider them to be dangerous? – Llama Feb 10 '20 at 09:31

2 Answers2

3

If Regex is not a requirement, then you could write a stringextension that returns a bool indicating if the value is valid or not.

public static class StringExtensions
{
    private static char[] invalidChars = { '<', '>', '&', '%', ';', '=', '{', '}', '(', ')' };

    public static bool IsValid(this string value)
    {
        if (value == null)
        {
            return false;
        }

        foreach (char c in invalidChars)
        {
            if (value.Contains(c))
            {
                return false;
            }
        }

        return true;
    }
}

Then you can check it like this:

static void Main(string[] args)
{
    string validString = "Hello World";
    string invalidString = "Hello (World)";

    Console.WriteLine($"{validString} --> {validString.IsValid()}");
    Console.WriteLine($"{invalidString} --> {invalidString.IsValid()}");
}

The code above produces this result:

Example

Lars Kristensen
  • 1,199
  • 18
  • 24
1

You can achieve that by using .Net's Regex.Replace() method.
Try something like this:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string input = @"(a>da <asd> fds&sd fsdf%dsf;sd f=sdf{sdf} asd(as)dfs";
        // NOTE: REPLACE the pattern with the one you need
        string pattern = @"<|>|&|%|;|=|{|}|\(|\)";
        string replacement = "";
        string result = Regex.Replace(input, pattern, replacement);

        Console.WriteLine("Original String: {0}", input);
        Console.WriteLine("Replacement String: {0}", result);                             
    }
}
Just Shadow
  • 7,001
  • 2
  • 40
  • 51