Search code examples
javascriptregexserver-side

Regex not working in Code behind for Server side validation


I have a js code for validating a textbox. But the problem is that, the same regex is not working in code behind. See the code:-

HTML for the same:-

<asp:TextBox ID="txtSearch" runat="server" class="txtfld-search" oncopy="return false" oncut="return false" onpaste="return false"></asp:TextBox>
        <asp:CustomValidator ID="CustomValidator1" runat="server" ForeColor="Red" ErrorMessage="Please enter numeric values."
OnServerValidate="Validate_Numeric" ControlToValidate="txtSearch"></asp:CustomValidator>


<script type="text/javascript">
$(document).ready(function () {
    $('#ctl00_topNavigation_txtSearch').keyup(function () {
        var $th = $(this);
        $th.val($th.val().replace(/[^.%a-zA-Z0-9 ]/g,
        function (str) {
            alert('Special characters not allowed except %');
            return '';
        }));
    });
});

I am using like this, but it is not working

    protected void Validate_Numeric(object sender, ServerValidateEventArgs e)
{
    System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("/[^.%a-zA-Z0-9 ]/g");
    e.IsValid = r.IsMatch(txtSearch.Text);
}

I want this /[^.%a-zA-Z0-9 ]/g, same regex to be used in Code-behind. Please help.


Solution

  • Not sure. May be this will help you. The answer will not fit you exactly. However, you will get an idea to overcome the issue.

    using System.Text.RegularExpressions;
    
    
    protected void Validate_Numeric(object sender, ServerValidateEventArgs e)
    {
        string Pattern = @"[^.%a-zA-Z0-9]";
        e.IsValid = Regex.IsMatch(txtSearch.Text, Pattern);    
    }