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.

            var formule = $(this).val();
            var valid_formule = formule.replace(CRAZY_REGEXP,'');

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 !


You may try something like this:

var re = /[^\]\d\(\)+\-*\/,.]+(?=[^\[\]\(\)]*(?:\[|\(|$))/g;
    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.

Need Your Help

Timer for DateTime on a label , error

c# winforms timer

i wanted to update my DateTime label every second.. i have this code.. but i get an error.. says " Cannot implicitly convert type 'System.TimeSpan' to 'int' "

Why can't I divide a fixnum by another fixnum?

ruby math division fixnum

I'm currently trying to divide counts["email"] a hash containing the number 82,000 by a variable total which contains the value 1.3 million.