简体   繁体   中英

JQuery Validate AddMethod for HTML Multiple Select

I am using Jquery validate addmethod for a multiple selection form. I do not understand the data / data types passed to the method (value, element) to be able to write my desired condition. The condition must check if there have been more than two options selected and if "Mixed" is one of the values, return an error. I have attached a screenshot of my debugging efforts to print object types and values. In my actual code, the condition I am performing (if value == 1) is obviously not working because of the data types it was just for testing.

Sample of Desired Functionality

$.validator.addMethod(
    "mixedbreed",
    function(value, element) {
        if ( value.length >= 2 && value.includes("Mixed") ) {
            return false;
        }
    },
    "Can't use 'Mixed' with other options"
);

HTML

<html>
    <head>
        <?php echo $html_head ?>
        <link rel="stylesheet" href="css/animal.css">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
    </head>
    <body>
        <?php echo $html_navigation ?>
        <h2 align="center">Edit Animal</h2>
            <div align="center" class="container">
                <form name="animal" id="animal" method="POST">
                    Breeds:
                    <select name="breeds[]" id="breeds" multiple>
                        <option>--Species Required--</option>
                    </select>
                    <input type="submit" name="animal_form" onclick="submitForm();"/>
                </form>
            </div>
    </body>
</html>

Breeds Data

<?php
    include_once('../resources/config.php');
    include_once('session.php');

    $result = sql_select_available_breeds("Cat");


    while( $row = pg_fetch_row($result) ) {
        echo sprintf("<option value='%s'>%s</option>",
                     $row[1], $row[1]);
    }
?>

JQuery

    function submitForm() {
        $.validator.addMethod(
            "mixedbreed",
            function(value, element) {
                if ( value.length == 1 ) {
                    return false;
                }
            },
            function(value, element) {
                return "Bad value: " + value + " " + element[0].text + " " + typeof element[0];
            }
        );

        var animal_validator = $("#animal").validate({
            rules: {
                'breeds[]': {
                    required: true,
                    mixedbreed: true
                }
            },
            errorElement: "span",
            messages: {
                'breeds[]': {
                    required: "b required "
                }
            }
        });
        if (animal_validator.form()) {
            $('form#animal').attr({
                action: 'mycontroller'
            });
            $('form#animal').submit();
        }
    }

Result

I was trying to understand the object types and data structures. I can't distinguish options that have been selected from not. 在此处输入图片说明

I was pretty close originally to understanding the data type. Below is the link that help me and my solution.

Options Looping

$.validator.addMethod(
// argument #1 = method name
"mixedbreed",
// argument #2 = condition
function(value, elements) {
    let selected = 0;
    let mixed = Boolean(false);
    for (let i = 0; i < elements.length; i++) {
        if (elements[i].selected) {
            selected++;
            if (elements[i].text == "Mixed") {
                mixed = true;
            }
        }
    }
    if (selected >= 2 && mixed) {
        return false;
    } else {
        return true;
    }
},
// argument #3 = error message
"'Mixed' not allowed with other breed(s)"
);

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