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,215
  • 1
  • 20
  • 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,410
  • 19
  • 29
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
  • 10,860
  • 6
  • 57
  • 75