0

I have this markup here and I wish to add a simple check to see if the user has selected a size. I am using the jQuery validation plugin I am not sure the best way to go about this. I can't change the markup because it's part of a custom cms.

        <form class="product-details">  
        <select class="w80 valid" id="mysize" required="required" title="Please select size!" name="mysize">
           <option value="11071">Select Size</option>
           <option value="11079">S</option>
           <option value="11080">M</option>
           <option value="11081">L</option>
           <option value="11082">XL</option>
           <option value="11089">XXL</option>
        </select>
        ...
        <button type="submit">Add</button>
        </form>

I know the logic would be something like this in vanilla jQuery:

        ( function($) {

           $(function (){  
               $('.product-details').submit(function(){
                 var mySize = $('#mysize');
                 var firstOption = mySize.find('option').first().val();
                 var userOption = mySize.find(':selected').val();
                 if( firstOption === userOption ) {
                    // fail
                    return false;
                    // trigger some error.
                 }
               });
           }); 

        } ) ( jQuery );

So how to use jQuery validate to do something similar.

1 Answer 1

1

Try

$(function(){
    jQuery.validator.addMethod( 'notequals', function(value, element, param){
        return value != param;
    } , 'Please select a valid value')

    $('.product-details').validate({
        rules: {
            mysize: {
                notequals: $('#mysize').find('option').first().val()
            }
        }
    });
});

Demo: Plunker

Sign up to request clarification or add additional context in comments.

1 Comment

Oh adding a new validation method AddMethod was the key. Thanks Arun!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.