jQuery Validate -只允许填充四个字段中的两个字段-如何验证

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

本文关键字:字段 两个 验证 何验证 Validate 填充 -只 四个 jQuery 许填充      更新时间:2023-09-26

我有四个输入字段:

MaxWidth
MaxHeight

Width
Height

我想验证只输入了MaxWidth + MaxHeightWidth + Height。用户不能同时提交两个集合的值

任何想法?


我正在使用jquery.validate.min.js提供的。net mvc默认应用程序

这就是我需要验证的

    <-- 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 />

我已经重写了我的表单,以反映Mohen在他回答的命令中描述的UI/UX设置。

但我会用"接受"的答案奖励Jayendra Patil,但我会"标记"Mohens的答案和建议

亲切的问候div ' T

您可以很容易地禁用其他输入当一个值。

例如,你有这两个输入:

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

,当用户输入width时,不允许输入maxwidth。然后你可以这样做:

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

对于width和maxwidth

也可以这样做

JsBin文件

你也可以尝试使用依赖验证。
添加一个方法来检查其他两个字段。
并使所需的依赖于另一个字段。

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

cmdMaxWidth字段示例(id硬编码,可以作为参数传递)-

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
                }   
            }
        }
    );
});