如何将jQuery验证用于非输入或替代方法



我正在尝试为非输入,自定义选择添加验证。我有一系列用户单击的图像,这些图像充当复选框,但实际上没有输入。我在其余表格中都使用jQuery验证,并且想看看是否有我可以添加验证的方法,它是否正在添加方法(我读过jQuery validate仅在输入上可以使用(或其他可以与一键一起使用的东西提交。

我想要类似的东西,但是要像jQuery validate一样工作。

if(checkValue.length < 1) {
    alert("You need at least one interested selected.");
}

我尝试将上述if-Statement放在验证代码中的规则部分上方,但会引发错误。

有人有我可以尝试的其他想法吗?

//Getting Value of the interest boxes
var interest = $('.interest');
var checkVal = '';
var checkValue = '';
interest.click(function() {
		checkVal = [];
		$(this).toggleClass('active');
		$('.interestBox', this).toggleClass('active');
		interest.each(function() {
			if($(this).is('.active')) {
				checkVal.push($(this).data('title'));
			}
		});
		checkValue = checkVal.join(', ');
		console.log(checkValue);
});
//Jquery Validate
$('#salesforce_submit').validate({
		rules: {
			first_name: {
				required: true,
				minlength: 2
			}
		},
		messages: {
			first_name: {
				required: "Please enter your first name",
				minlength: "Your first name seems a bit short, doesn't it?"
			}
		},
		submitHandler: function(form) {
			event.preventDefault();
			var datastring = $('#salesforce_submit').serialize();
			$.ajax({
				url: '/php/quoteSend.php',
				type: 'POST',
				data: datastring
				,
				success: function(data) {
					if (data == 'Error!') {
						alert(data);
					} else {
					}
				},
				error: function(xhr, textStatus, errorThrown) {
					alert(textStatus + '|' + errorThrown);
					console.log('error');
				}
			});
		}
	});
.interest img {
  height: 50px;
  width: 50px;
} 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form id="salesforce_submit" type="Post">
<div><input id="first_name" placeholder="First Name*" class="input block" maxlength="40" name="first_name" type="text"></div>
<h3 class="interestTitle">A</h3>
<div class="interest" data-title="A">
  <img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="A">
</div>
<h3 class="interestTitle">B</h3>
<div class="interest" data-title="B">
  <img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="B">
</div>
<h3 class="interestTitle">C</h3>
<div class="interest" data-title="C">
  <img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="C">
</div>
<input type="Submit" value="Submit">

完整代码:

<section class="sec90">
            <h3 class="subTC">Enter your information below.</h3>
            <form action="" id="salesforce_submit" method="POST" enctype="multipart/form-data">
                <input name="oid" type="hidden" value=""><input type="hidden" id="" id="interestValue" multiple="multiple" name="" value=""><input name="retURL" type="hidden"> <input name="lead_source" required="" type="hidden" value="Quote Form"> <input id="txt_medium" name="txt_medium" type="hidden" value=""> <input id="txt_source" name="txt_source" type="hidden" value=""> <input id="txt_campaign_name" name="txt_campaign_name" type="hidden" value=""> <input id="txt_term" name="txt_term" type="hidden" value=""> <input id="txt_content" name="txt_content" type="hidden" value="">
                <div><input id="first_name" placeholder="First Name*" class="input block" maxlength="40" name="first_name" type="text"></div>
                <div><input id="last_name" placeholder="Last Name*" class="input block" maxlength="80" name="last_name" type="text"></div>
                <div><input id="email" placeholder="Email*" class="input block" maxlength="80" name="email" type="email"></div>
                <div><input id="phone" placeholder="Phone* no dashes" class="input block" maxlength="12" name="phone" type="tel"></div>
                <div><input id="zip" placeholder="Zip/Postal Code*" class="input block" maxlength="5" name="zip" type="text" pattern= "[0-9]{5}"></div>
                <div><input id="company" placeholder="Company*" class="input block" maxlength="40" name="company" type="text"></div>
        </section>
        <section class="sec90">
                <h3 class="subTC">What are you interested in?*</h3>
                <div><input type="hidden" name="interestHidden" value=""></div>
        <section class="sec90" id="up">
                <h3 class="subTC">Describe your project*</h3>
                <div><textarea id="description" name="description" placeholder="Provide as much detail as possible"></textarea></div>
                <h3 class="subTC block">Have a .stp file or drawing example? Send it for quicker quote times.</h3>
                <input type="file" name="uploadedFile" class="inputfile" id="uploadedFile" data-multiple-caption="{count} files selected" multiple>
                <label for="uploadedFile" class="button"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" viewBox="0 0 20 17"><path d="M10 0l-5.2 4.9h3.3v5.1h3.8v-5.1h3.3l-5.2-4.9zm9.3 11.5l-3.2-2.1h-2l3.4 2.6h-3.5c-.1 0-.2.1-.2.1l-.8 2.3h-6l-.8-2.2c-.1-.1-.1-.2-.2-.2h-3.6l3.4-2.6h-2l-3.2 2.1c-.4.3-.7 1-.6 1.5l.6 3.1c.1.5.7.9 1.2.9h16.3c.6 0 1.1-.4 1.3-.9l.6-3.1c.1-.5-.2-1.2-.7-1.5z"/></svg><span class="marL5">Upload file</span></label>
                <input type="hidden" name="MAX_FILE_SIZE" value="10000000">
                <div class="margBot40"></div>
        </section>
                <input name="submit" class="block testB" type="submit" value="SUBMIT QUOTE">
            </form>

JS:

var interest = $('.interest');
    var checkVal = '';
    var checkValue = '';
    var showMe = '';
    interest.click(function() {
        checkVal = [];
        $(this).toggleClass('active');
        $('.interestBox', this).toggleClass('active');
        interest.each(function() {
            if($(this).is('.active')) {
                checkVal.push($(this).data('title'));
            }
        });
        checkValue = checkVal.join(', ');
        console.log(checkValue);
        //Hidden interest input value
        var checkLength = checkVal.length;
        console.log(checkLength);
        $('[name="interestHidden"]').val(checkLength);
        var interestVal = $('interestValue').val() 
        interestVal = checkValue;
        showMe = interestVal;
        console.log('Hidden val is ' + showMe); 
    });
    /*$('#phone').keyup(function() {
        $(this).val($(this).val().replace(/(d{3})-?(d{3})-?(d{4})/,'$1-$2-$3'));
    });*/
    $('#phone').keydown(function (e) {
        var key = e.charCode || e.keyCode || 0;
        $text = $(this);
        if (key !== 8 && key !== 9) {
            if ($text.val().length === 3) {
                $text.val($text.val() + '-');
            }
            if ($text.val().length === 7) {
                $text.val($text.val() + '-');
            }
        }
        return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
    });
    var inputs = document.querySelectorAll( '.inputfile' );
    Array.prototype.forEach.call( inputs, function( input )
    {
        var label    = input.nextElementSibling,
            labelVal = label.innerHTML;
        input.addEventListener( 'change', function( e )
        {
            var fileName = '';
            if( this.files && this.files.length > 1 )
                fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length );
            else
                fileName = e.target.value.split( '\' ).pop();
            if( fileName )
                label.querySelector( 'span' ).innerHTML = fileName;
            else
                label.innerHTML = labelVal;
        });
    });
    $('#phone').keyup(function() {
        jQuery.validator.addMethod("alphanumeric", function(value, element) {
            //return this.optional(element) || /^[a-z0-9-]+$/i.test(value);
            return this.optional(element) || /^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-s./0-9]*$/i.test(value);
        }, "Numbers and dashes only");
    });
    $('#salesforce_submit').validate({
        ignore: [],
        rules: {
            first_name: {
                required: true,
                minlength: 2
            },
            last_name: {
                required: true,
                minlength: 2
            },
            email: {
                required: true,
                email: true
            },
            phone: {
                required: true,
                //digits: true,
                minlength: 10,
                alphanumeric: true
            },
            zip: {
                required: true,
                digits: true,
                minlength: 5
            },
            company: {
                required: true,
                minlength: 2
            },
            interestHidden: {
                required: true,
                min: 1
            }/*,
            description: {
                required: true,
                minlength: 5
            }*/
        },
        messages: {
            first_name: {
                required: "Please enter your first name",
                minlength: "Your first name seems a bit short, doesn't it?"
            },
            last_name: {
                required: "Please enter your last name",
                minlength: "Your last name seems a bit short, doesn't it?"
            },
            email: {
                required: "Please enter your email address",
                email: "Please enter a valid email address"
            },
            phone: {
                required: "Please enter your phone number",
                digits: "Please enter a valid phone number with only numbers",
                minlength: "Your number seems a bit short, doesn't it?"
            },
            zip: {
                required: "Please enter your zip code",
                digits: "Please enter a valid zip code with only numbers",
                minlength: "Your zip code seems a bit short, doesn't it?"
            },
            company: {
                required: "Please enter your company name",
                minlength: "Your company name seems a bit short. Please enter at least 2 characters"
            },
            interestHidden: {
                required: "Please choose at least one interest",
                min: "At least one interest needs chosen"
            }/*,
            description: {
                required: "Please enter your project description",
                minlength: "Your description seems a bit short, doesn't it?"
            }*/
        },
        submitHandler: function(form) {
            event.preventDefault();
            var datastring = $('#salesforce_submit').serialize();
            $.ajax({
                url: '/php/quoteSend.php',
                type: 'POST',
                data: datastring
                ,
                success: function(data) {
                    console.log(data);
                    if (data == 'Error!') {
                        alert('Unable to submit form!');
                        alert(data);
                    } else {
                        $('#salesforce_submit')[0].reset();
                        $('#consult-success').show();
                        $('#salesforce_submit').hide();
                    }
                },
                complete: function() {
                    //$("#salesforce_submit").submit();
                    location.href = "";
                },
                error: function(xhr, textStatus, errorThrown) {
                    alert(textStatus + '|' + errorThrown);
                    console.log('error');
                }
            });
        }
    });

由于jQuery验证仅验证 selecttextarea和各种类型的 input elements 1 ,您唯一的选择就是给它所需的东西。

创建一个隐藏的元素...

<input type="hidden" name="myImage" value="0" />

用户单击您的图像时,请使用jQuery操纵type="hidden" input元素的值...

$('#photo').on('click', function() {
    $('[name="myImage"]').val('1');
});

然后以编程性验证其值。由于单击图像不会引起任何验证,因此您可以使用.valid()方法触发这些隐藏元素的验证...

$('[name="myImage"]').valid(); 

您将需要利用ignore选项,因为该插件默认情况下不会验证隐藏元素。ignore: []将有效禁用此功能并强制插件验证所有隐藏元素...

$('#salesforce_submit').validate({
    ignore: [],
    rules: { ....

当然,您还需要制定适当验证隐藏元素价值的规则。

由于该消息将放置在隐藏元素附近,因此您必须利用errorPlacement函数以条件放置此消息。

$('#salesforce_submit').validate({
    ignore: [],
    errorPlacement: function(error, element) {
        if (element.attr('name') == 'myImage') {
            // placement for hidden element
        } else {
            // default
            error.insertAfter(element);
        }
    }
    rules: { ....

1 插件的新版本还用contenteditable属性支持元素。

这又如何,给所有复选框触发相同的名称,例如"盒子"。添加此自定义规则" img_check":

 jQuery.validator.addMethod("img_check", function() {
        $(input[name='box']).each( function(){
                     if $(this).is(':checked') {
                         return true
                     }
                })
                // No box was checked
                return false
}, "Please check at least one box");

然后添加此规则:

rules: {
        first_name: {
            required: true,
            minlength: 2
        },
        box[]: {
           img_check: true
           }
    },

为什么不在进行提交过程之前检查checkValue

//Getting Value of the interest boxes
var interest = $('.interest');
var checkVal = '';
var checkValue = '';
interest.click(function() {
		checkVal = [];
		$(this).toggleClass('active');
		$('.interestBox', this).toggleClass('active');
		interest.each(function() {
			if($(this).is('.active')) {
				checkVal.push($(this).data('title'));
			}
		});
		checkValue = checkVal.join(', ');
		console.log(checkValue);
});
//Jquery Validate
$('#salesforce_submit').validate({
		rules: {
			first_name: {
				required: true,
				minlength: 2
			}
		},
		messages: {
			first_name: {
				required: "Please enter your first name",
				minlength: "Your first name seems a bit short, doesn't it?"
			}
		},
		submitHandler: function(form) {
    if(checkValue.length>0){
			event.preventDefault();
			var datastring = $('#salesforce_submit').serialize();
			$.ajax({
				url: '/php/quoteSend.php',
				type: 'POST',
				data: datastring
				,
				success: function(data) {
					if (data == 'Error!') {
						alert(data);
					} else {
					}
				},
				error: function(xhr, textStatus, errorThrown) {
					alert(textStatus + '|' + errorThrown);
					console.log('error');
				}
			});
      }else console.log('Please select at least one interest');
		}
	});
  
.interest img {
  height: 50px;
  width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form id="salesforce_submit" type="Post">
<div><input id="first_name" placeholder="First Name*" class="input block" maxlength="40" name="first_name" type="text"></div>
<h3 class="interestTitle">A</h3>
<div class="interest" data-title="A">
  <img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="A">
</div>
<h3 class="interestTitle">B</h3>
<div class="interest" data-title="B">
  <img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="B">
</div>
<h3 class="interestTitle">C</h3>
<div class="interest" data-title="C">
  <img src="https://www.mountaineers.org/images/placeholder-images/placeholder-400-x-400/image_preview" alt="C">
</div>
<input type="Submit" value="Submit">

相关内容

  • 没有找到相关文章

最新更新