0

我正在学校实验室工作,目标是创建一个 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”。)尝试设置子字符串的长度似乎不起作用。当前示例中的条件似乎也仅在字符串仅包含“-”时才有效。添加的任何额外字符都不会触发它。

代码:

    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
4

1 回答 1

0

使用正则表达式对象:

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

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

-?1 个可选 -

\$ 1 强制性 $

\d+ 1 位或多位数字

. 强制性的。

\d{2} 正好 2 位数字

$/ 强制结束字符串

于 2016-02-27T01:28:48.160 回答