javascriptjqueryjquery-uijquery-validatejquery-ui-spinner

Validate a jQuery-UI Spinner within a form


I'm using the "jQuery Validation Plugin" to validate the form fields. It works very well.

I added a new field into the form. This field use a jQuery-UI Spinner, but I have no success to validate it.

This is th HTML code of the spinner element:

<form id="formAddCategory">
    <input id="spinTeamNumber" name="value" style="display: inline-block; margin: 10px; width: 3em;" size="3" maxlength="3">
</form>

This is the spinner code:

$("#spinTeamNumber").spinner({
    step : 1,
    min : 1,
    numberFormat : "n",
    alignment : 'vertical'
});

This is the validation code:

$("#formAddCategory").validate({
    rules : {
        "spinTeamNumber" : {
            required : true,
        }
    },
    messages : {
        "spinTeamNumber" : {
            required : "* Required"
        }
    }
});

[...]

if ($("#formAddCategory").valid()) {
    ...
}

But it does not work. I also tried to define a custom validation method, but without success.


Solution

  • You can only use the name, not the id, of the input element within the .validate() method.

    Your name is defined as value...

    <input id="spinTeamNumber" name="value" ....
    

    So you must use value within the .validate() method...

    $("#formAddCategory").validate({
        rules : {
            value : {  // <-- the input NAME
                required : true,
            }
        },
        messages : {
            value : {  // <-- the input NAME
                required : "* Required"
            }
        }
    });
    

    To create the spinner, jQuery UI dynamically adds a container around the original input element, so you'll probably want to use the errorPlacement option to get the message to display on the outside.

    DEMO: http://jsfiddle.net/6u18p6ju/