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

时间:2018-04-02 20:11:30

标签: javascript jquery jquery-validate

我正在尝试为非输入的自定义选择添加验证。我有一系列用户点击的图像,它们充当复选框,但实际上没有输入。我正在使用jQuery验证表单的其余部分,并希望看看是否还有我可以添加验证,是否添加方法(我读取jQuery验证仅适用于输入)或其他只需单击即可工作的东西提交。

我想要类似于此的东西,但像jQuery验证一样工作。

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

我尝试将上面的if语句放在验证代码中的规则部分之上,但它会引发错误。

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

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

3 个答案:

答案 0 :(得分:1)

由于jQuery Validate仅验证selecttextarea和各种类型的input元素 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属性的元素。

答案 1 :(得分:0)

怎么样,给你触发相同名称的所有复选框,例如&#34;盒&#34 ;.添加此自定义规则&#34; img_check&#34;:

 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
           }
    },

答案 2 :(得分:-1)

为什么在继续提交过程之前不检查//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'); } });

&#13;
&#13;
.interest img {
  height: 50px;
  width: 50px;
}
&#13;
<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">
&#13;
null
&#13;
&#13;
&#13;