开发者

jQuery Validate - Only two fields of four allowed to be filled - how to validate?

开发者 https://www.devze.com 2023-04-12 02:08 出处:网络
I have four input fields: MaxWidth MaxHeight and Width Height I want to validate that only MaxWidth + MaxHeight or Width + Height has been entered. The user shouldn\'t be able to submit values f

I have four input fields:

MaxWidth
MaxHeight

and

Width
Height

I want to validate that only MaxWidth + MaxHeight or Width + Height has been entered. The user shouldn't be able to submit values for both sets.

Any idea?


Update

i'm using the jquery.validate.min.js supplied with .NET MVC3 default application

This is what i basicly need validation of

    <-- Scale a picture to one of the max attributes and keeping the aspect ratio --/>
    <input type="text" name="cmdMaxWidth" /><br />
    <input type="text" name="cmdMaxHeight" /><br />
    <br />
    <-- Scale a picture to the exact width and height attributes, still keeping the aspect ratio but addting whitespace for the rest --/>
    <input type="text" name="cmdWidth" /><br />
    <input type="text" name="cmdHeight" /><br />

Update

I've rewritten my form to reflect the UI/UX setup descriped by Mohen in the commands on his answer.

BUT i'll reward Jayendra Patil with the "accepted" answer, but i'll "flag up" Mohens answers and suggestions

Kind Re开发者_StackOverflowgards \T


You can easily disable other input when one is get a value.

For example you have this two inputs:

 <input id="width" placeholder="width"/>
  <input id="maxwidth" placeholder="max width"/>

and you want to not allow maxwidth entered when user entered width. Then you can do this:

$('#width').change(function(){
  if($(this).val() != ''){
    $('#maxwidth').attr('disabled', 'disabled');
  }
});

You can do same vise versa for width and maxwidth

JsBin File


you can also try to use validation with dependency.
Add a method which will check for the other two fields.
And make the required dependent on the other field.

Demo - http://jsfiddle.net/b3RmV/

Example for cmdMaxWidth field (ids hardcoded, you can pass as params)-

jQuery.validator.addMethod("allowed", function(value, element) {
    return !($('#cmdWidth').val().length > 0 || $('#cmdHeight').val().length > 0)

}, "Not allowed");

$(document).ready(function(){
    $("#commentForm").validate(
        {   rules: {     
                cmdMaxWidth: {       
                    required:  function(element){
                      return $('#cmdMaxHeight').val().length > 0;
                    },
                    allowed: true
                }   
            }
        }
    );
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号