ValidationExpression to allow single space using JavaScript in ASP.Net

samsmuthu
 
on Oct 06, 2021 10:38 PM
488 Views

Hi 

ValidationExpression for A - z and 0 - 9 except special characters and allow single space

Reference article of

ValidationExpression to restrict specified charterers in ASP.Net

i have create a following code

<asp:TextBox runat="server" ID="txtASP"></asp:TextBox>
<asp:RegularExpressionValidator runat="server" ID="RegularExpression1" ControlToValidate="txtASP"
ErrorMessage="#%&{}\<>*?/ $':@+`|=&quot; not allowed" ValidationExpression="[^#%&{}\\<>*?/\s$':@+`|=&quot;]*$">
</asp:RegularExpressionValidator>
<br />
<asp:Button runat="server" ID="btnSave" Text="SAVE" />

so i want to allow 'space',  please advise me.

Thanking you

samsmuthu

Download FREE API for Word, Excel and PDF in ASP.Net: Download
arjunv
 
on Oct 08, 2021 05:28 AM

Dear samsmuthu, 

  This will not be possible with the help of Regular Expression Validation. You have to use Custom Validator. code given below.

HTML

<asp:TextBox runat="server" ID="txtASP"></asp:TextBox>
<asp:CustomValidator runat="server" ClientValidationFunction="Validate" ControlToValidate="txtASP" ErrorMessage="Invalid" />
<script type="text/javascript">
    function Validate(sender, args) {
        var key = document.getElementById(sender.controltovalidate).value;
        var spKeys = new Array();
        spKeys.push("#");
        spKeys.push("%");
        spKeys.push("&");
        spKeys.push("{");
        spKeys.push("}");
        spKeys.push("\\");
        spKeys.push("<");
        spKeys.push(">");
        spKeys.push("*");
        spKeys.push("?");
        spKeys.push("/");
        spKeys.push("$");
        spKeys.push("'");
        spKeys.push(":");
        spKeys.push("@");
        spKeys.push("+");
        spKeys.push("`");
        spKeys.push("|");
        spKeys.push("=");
        spKeys.push("\"");
        if (key.indexOf("  ") == -1) {
            for (var i = 0; i < key.length; i++) {
                if (spKeys.indexOf(key.charAt(i)) == -1) {
                    args.IsValid = true;
                }
                else {
                    args.IsValid = false;
                    return false;
                }
            }
        } else {
            args.IsValid = false;
            return false;
        }
    }
</script>

Screenshot