Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

jquery validator plugin - no validation

I know this suppose to be simple (according to the plugin page anyway)

But I'm trying to use the plugin with no success, here's my form:

<form id="mongoForm">
        <label for="skip">skip:</label> <input type="text" id="skip"
            style="width: 70px">
        <p />
        limit: <span id="limitLable" style="border: 0">1</span>
        <div id="limit" style="width: 250px"></div>
        <p />
        <label for="collection">collection: </label> <input type="text"
            id="collection">
        <p />
        <label for="sort">sort: </label> <input type="text" id="sort">
        <p />
        <label for="type">type: </label><select id="type">
            <option value="find" selected="selected">find</option>
            <option value="count">count</option>
        </select>
        <p />
        <label for="query">query: </label>
        <textarea rows="10" cols="80" id="query"></textarea>
        <input type="submit" value="execute" id="execute">
    </form>

and my jquery script:

$(document).ready(function() {
    $.validator.addMethod("validJson", function(value, element) {
        try {
            var val = $.parseJSON(value);
            return true;
        } catch (e) {
            return false;
        }

    }, "Invalid JSON string");
    $("#mongoForm").validate({
        rules : {
            collection : {
                required : true
            },
            query : {
                validJson : true
            }
        },
        submitHandler : function(form) {
            queryServer();
        }
    });

But, the validation is not working. If I add a class="required" to the inputs, it works for custom validations, but not for my custom validJson method. But this does not solve my problem as some fields are not required I just need to validate optional values

Any ideas please?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you need name attributes, as explained in the general guidelines:

The name attribute is required for input elements, the validation plugin doesn't work without it. Usually name and id attributes should have the same value.

so markup should be

<label for="collection">collection:</label> 
<input type="text" id="collection" name="collection">

etc


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...