简体   繁体   中英

Using JQuery.Validator AddMethod to validate stock symbol

I am new to coding and I am not exactly sure what I am doing wrong here, but I am just to validate an input in a form against a few stock symbols. When I submit an symbol that isn't in the array, I do not receive the error message. My code is below.

<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加载后初始化此函数

You've created a new rule called vsymbol . However, when you use it, you've misspelled it as symbol . You must reference it correctly in order for it to get used...

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

If you've already assigned the rule via the rules object above, then it's totally redundant to assign it again within the field's class . Just use one or the other.

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

Also, since your form's HTML markup comes after your JavaScript, your jQuery needs to be wrapped in a DOM ready event handler.

<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>

You may want to read this regarding your use of Allman coding style within JavaScript .

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