user1488957
user1488957

Reputation: 33

Validation of a mathematical formula based on user input

I know that SO is not a code generator, but I break my head and I'll got mad with this RegExp.

I've <input /> type text, in a HTML <form />. The input is automatically filled when the user double-click on elements in a specific list.
This event will generate string like "[text:number]" or "[text:number:text]", and place it at the cursor position in my <input /> field.
The first goal of this process is to construct a mathematic formula structure. I mean, the generated strings between brackets will insert elements, then I want to allow the user to put only numbers and operators.

I've tried to bind the keydown event, and test the char with String.fromCharCode(e.which); but for the keys "+" or "-" (and other operators) this function returns alphabeticals chars. Without success.
Then, I've finally decided to use the keyup event, then use a RegExp to replace the <input /> value.

        $("#inputID").keyup(function(){
            var formule = $(this).val();
            var valid_formule = formule.replace(CRAZY_REGEXP,'');
            $(this).val(valid_formule);
        });


So, my question is as follows :
How construct a javascript RegExp, to remove all chars which are not between brackets, and which are differents of ()+-*/,. and numbers.
An example :
"a[dse:1]a+a[dse:5]a+a[cat:5:sum]a+(a10a/5,5)!"
will become
"[dse:1]+[dse:5]-[cat:5:sum]+(10/5,5)"

I'm open to another way to achieve my goal if you have some ideas. Thanks !

Upvotes: 3

Views: 3436

Answers (1)

MaxArt
MaxArt

Reputation: 22617

You may try something like this:

var re = /[^\]\d\(\)+\-*\/,.]+(?=[^\[\]\(\)]*(?:\[|\(|$))/g;
$("#inputID").keyup(function(){
    this.value = this.value.replace(re, "");
});

Keep in mind, though, that you have to be sure that the parenthetical structure is coherent with your syntax.

Advice: use RegExr to test your regular expressions, but remember that it's more powerful than Javascript regex support.

Upvotes: 4

Related Questions