validate custom method
http://stackoverflow.com/questions/10132998/validating-dropdown
by ryleyb
HTML
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<div class="grid_6">
<div class="box">
<div class="header">
<img src="http://www.kansasoutlawwrestling.com/kowmanager/assets/img/icons/packs/fugue/16x16/document--plus.png" alt="" width="16" height="16" />
<h3>Create a News Article</h3>
</div>
<form method="post" accept-charset="utf-8" id="newArticleForm" enctype="multipart/form-data"> <div class="content no-padding">
<div class="section _100">
<label for="title">Title</label>
<div>
<input type="text" name="title" value="" /> </div>
</div>
<div class="section _100">
<label for="category">Category</label>
<div>
<select name="category">
<option value="" selected="selected">Please Select An Opion</option>
<option value="4">Columns</option>
<option value="2">Headlines</option>
<option value="1">Main News</option>
<option value="3">Rumors</option>
</select> </div>
</div>
<div class="section _100">
<label for="sticky">Is Sticky</label>
<div>
<select name="sticky">
<option value="-1">Please Select An Option</option>
<option value="0">No</option>
<option value="1">Yes</option>
</select> </div>
</div>
<div class="section _100">
<label for="comments">Allow Comments</label>
<div>
<select name="comments">
<option value="-1">Please Select An Option</option>
<option value="0">No</option>
<option...
CSS
label.error{ color: red; }
JavaScript
$.validator.addMethod("valueNotEquals", function (value, element, arg) {
return arg != value;
}, "Message to User");
var validateform = $("#newArticleForm").validate({
rules: {
title: {
required: true,
minlength: 5
},
category: {
required: true,
valueNotEquals: "-1"
},
sticky: {
required: true,
valueNotEquals: "-1"
},
comments: {
required: true,
valueNotEquals: "-1"
},
datetime: {
required: true,
date: true
},
status: {
required: true
},
file: {
required: true,
accept: 'png|jpe?g|gif'
},
permalink: {
required: true
},
article: {
required: true,
minlength: 5
}
},
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
console.log('found errors');
} else {
console.log('no errors');
}
},
showErrors : function(errorMap, errorList) {
this.defaultShowErrors();
var self = this;
$.each(errorList, function() {
var $input = $(this.element);
var $label = $input.parent().find('label.error').hide();
$label.addClass('red');
$label.css('width', '');
$input.trigger('labeled');
$label.fadeIn();
});
},
submitHandler: function(form) {
var dataString = $('#newArticleForm').serialize();
$.ajax({
type: 'POST',
url: 'dashboard/articleSubmit',
data: dataString,
dataType: 'json',
success: function(data) {
if (data.error) {
$('.box .content').removeAlertBoxes();
$('.box .content').alertBox(data.message, {type:...