繁体   English   中英

使用JQuery.Validator AddMethod验证股票代码

[英]Using JQuery.Validator AddMethod to validate stock symbol

我是编码的新手,我不确定在这里做错什么,但是我只是用几种股票代码来验证输入形式。 当我提交不在数组中的符号时,我不会收到错误消息。 我的代码如下。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>

<script>
jQuery.validator.addMethod("vsymbol", function(value) 
{
    var symbols = ["GOOG", "AAPL", "MSFT", "DIS"];
        var in_array = $.inArray(value.toUpperCase(), symbols);
        if (in_array == -1) 
    {
        return false;
        }
    else
    {
        return true;
        }
}, "Not a valid stock symbol");

$("#myform").validate(
{
  rules: {
    symbol: {
      required: true,
      symbol: true
        }
         }
}   
);
</script>

<body>
<form id="myform" >
<label for="symbol">Ticker</label>    
<input name="symbol" type="text" class="vsymbol" />
</form>
</body>

请在$(document).ready(function(){})中包装您的代码,以便在dom加载后初始化此函数

您已经创建了一个名为vsymbol的新规则。 但是,在使用它时,您将其拼写为symbol 您必须正确引用它才能使用它...

$("#myform").validate({
    rules: {
        symbol: { // <- name of the field
            required: true,
            vsymbol: true // <- name of the rule
        }
    }
});

如果您已经通过上面的rules对象分配了规则,那么在字段的class再次分配它完全是多余的。 只需使用其中一个即可。

<input name="symbol" type="text" class="vsymbol" />

另外,由于表单的HTML标记位于JavaScript之后,因此jQuery需要包装在DOM ready事件处理程序中。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.js"></script>

<script>
    $(document).ready(function() {  // DOM ready event handler

        jQuery.validator.addMethod("vsymbol", function(value) {
            var symbols = ["GOOG", "AAPL", "MSFT", "DIS"];
            var in_array = $.inArray(value.toUpperCase(), symbols);
            return (in_array == -1) ? false : true;
        }, "Not a valid stock symbol");

        $("#myform").validate({
            rules: {
                symbol: { // <- name of the field
                    required: true,
                    vsymbol: true // <- name of the rule
                }
            }
        });

    });
</script>

您可能需要阅读有关在JavaScript中使用Allman编码样式的信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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