简体   繁体   中英

regular expression validation using javascript

I need to validate a text based upon a regular expression in javascript. My regular expression is working fine but but can't find out why it is not working in java script.

The regular expression is this , ^([-+/*]\\d+(\\.\\d+)?)*

Valid expressions are +7 or +9.36*8 or +4-9.3/5.0

Invalid matches are test or 8.36

Here is the code,

    var ck_diffrentialformula = /^([-+/*]\d+(\.\d+)?)*/;

            function radtxtbxLinkedDifferentialFormulaOnBlur(sender, eventArgs) {
                if (sender.get_value().length > 0) {

                    var entered_value = sender.get_value();

                    if (ck_diffrentialformula.test(entered_value)) {
                     alert('Text Matches');
                    }
                    else {
                     alert('Text does not match');
                    }
                }
            }

sender.get_value() - gives the text box value over here.

Please tell me where I am doing wrong.

I'm assuming you're using it something like this:

<input type="text" onchange="radtxtbxLinkedDifferentialFormulaOnBlur(this,null)" />

sender has no method .get_value() so that won't even work. Replacing that, it seems to work.

function radtxtbxLinkedDifferentialFormulaOnBlur(sender, eventArgs) {
    console.log(sender)
    if (sender.value.length > 0) {
        console.log(sender.value);
        if (ck_diffrentialformula.test(sender.value)) {
         console.log('Text Matches');
        }
        else {
         console.log('Text does not match');
        }
    }
}

Maybe you want to try this expression: /^([\\-+\\/*]\\d+(\\.\\d+)?)*$/
It escapes "-" and "/" (jsbin suggests it) within the regex and considers the whole string ( $ at the end).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM