自动删除新字符javascript

时间:2016-02-27 01:12:30

标签: javascript if-statement user-controls enforcement

我在实验室上学,目标是创建一个Web控件,只接受用户的货币价值。

Rules:
1st digit must be “-“ or “$”
2nd digit must be “$” or a number
3rd digit on must be a number or a “.”
Only two digits after decimal
Must have a “$”

我遇到的问题是,虽然我可以设置标签以便在有或不允许的情况下显示,但我无法弄清楚如何在条件允许时自动删除新字符没有得到满足。 (EG不能输入" -1",只有" - $"或" $ 1"。)尝试设置子字符串' s长度似乎不起作用。当字符串仅由" - "组成时,当前示例中的条件似乎也起作用。添加的任何额外字符都不会触发它。

代码:

    function text2money(e) {
        // get value of txt
        var str = document.getElementById("<%=txt.ClientID %>").value;

        if (str.substring(0, str.length) === "-" && str.substring(1, str.length) !== "$") {
                str.length = 2;
        }

        // goes through string one character at a time, converts them to char, then checks if char is a decimal digit
        if (str.substring(0, 1) === ('-') || str.substring(0, 1) === ('$')) {
            document.getElementById("<%= lbl1.ClientID %>").innerHTML = "True"; // must use .innerHTML with labels

            // check if second digit is '$' or numeric
            if (str.substring(1, 2) === ("$") || isFinite(str.substring(1, 2))) {
                document.getElementById("<%= lbl1.ClientID %>").innerHTML = "It's numeric";

                // check if third and any future characters are '.' or numeric

            } // end second char if

            else {
                document.getElementById("<%= lbl1.ClientID %>").innerHTML = "Second char must be '$' or numeric";
            } // end second char

        } // end first char if
        else {
            document.getElementById("<%= lbl1.ClientID %>").innerHTML = "First character must be '-' or '$'";
        } // end first char

        // check if $ is included anywhere in the string
        var result = str.indexOf("$") <= -1; // -1 == false
        if (result) {
            document.getElementById("<%= lbl2.ClientID %>").innerHTML = "$ is a required character";
            }
            else {
                document.getElementById("<%= lbl2.ClientID %>").innerHTML = "";
            }

        } // end text2money

1 个答案:

答案 0 :(得分:0)

使用Regex对象:

        (/^-?\$\d+\.\d{2}$/).test(inputString)

/ ^将模式的开始定义为字符串的开头

- ? 1个可选 -

\ $ 1强制性$

\ d + 1位或更多位数

。强制性的。

\ d {2}正好是2位

$ /必须结束字符串