Rafał Saltarski
Rafał Saltarski

Reputation: 707

check a textbox for invalid characters using js and regular expressions

I am having a hard time figuring out how RegExp work.

I need to rewrite some ASP code into html and js, and I've hit an obstacle in this part:

<asp:RegularExpressionValidator runat="server" id="RegExpValidator" controltovalidate="FileName" Display="Dynamic" ValidationExpression="[^#%&*:<>?/{|}]+">

Now, what I do is create an input textbox which will run a js function whenever its content is changing.

<input type="text" id="fileNameTextBox" class="ms-input" size="35" maxlength="123" onchange="regexValidator(this);"/>

function regexValidator(control) {
            var val = $(control).val();
            if(val == undefined || val == '') {

                $(control).attr("class", "invalid");
            } 
            else { 
            // Regex stuff goes in here
            }
        }

Now, for the life of me I can't figure out how to construct the regular expression. The ValidationExpression field i assume checks for invalid characters though it doesn't seem to be a properly constructed regex, and I can't figure out how to write it into a proper one to use with js. Could someone help me out with this?

Upvotes: 3

Views: 16386

Answers (3)

FixMaker
FixMaker

Reputation: 3877

[^#%&*:<>?/{|}]+ looks like a valid expression to me (although typically regular expressions are enclosed in forward-slashes). It's basically checking to see of the filename contains any of the illegal characters within the square brackets (apart from the caret ^ which indicates negation).

function regexValidator(control) {
        var val = $(control).val();
        if(val == undefined || val == '') {

            $(control).attr("class", "invalid");
        } 
        else if(val.match(/[^#%&*:<>?/{|}]+/)) {
            // Valid
        }
        else {
            // Invalid
        }
    }

Upvotes: 2

pogo
pogo

Reputation: 1550

If you want the regex to check for invalid characters in the field, you can use this.

^.*?(?=[\^#%&$\*:<>\?/\{\|\}]).*$ This will give you a match if there is at least one invalid character.

Upvotes: 4

Martin Ender
Martin Ender

Reputation: 44259

You are almost there. Now you just need to make sure, that your string only consists of valid characters. Do this by adding anchors for the beginning and end of string, thus ensuring that the repeated sequence covers the whole string:

ValidationExpression="^[^#%&*:<>?/{|}]+$"

EDIT: I just realised that you probably also want to know how to create a regular expression from a string. You can simply pass a string to a regex constructor:

new RegExp(validationExpressionGoesHere);

Upvotes: 3

Related Questions