Skip to content

Instantly share code, notes, and snippets.

@oomlaut
Created May 10, 2013 16:57
Show Gist options
  • Save oomlaut/5555745 to your computer and use it in GitHub Desktop.
Save oomlaut/5555745 to your computer and use it in GitHub Desktop.
Using jQuery.validate, compare the values of input fields against one another, create notifications based on similarity rules
$.validator.addMethod("similarity", function(value, element, params){
var acceptable = .25;
function mush(str){
str = str.replace(/[ \?|\.|!|\(|\)|\\|\/]/g, '').toLowerCase();
var arr = [];
for(var i = 0; i <= str.length - 1; i++){
arr.push(str[i]);
}
return arr.sort();
}
function intersection_destructive(a, b)
{
var result = new Array();
while( a.length > 0 && b.length > 0 )
{
if (a[0] < b[0] ){ a.shift(); }
else if (a[0] > b[0] ){ b.shift(); }
else /* they're equal */
{
result.push(a.shift());
b.shift();
}
}
return result;
}
var $this = $(element);
$this.parent().siblings().find('[data-type="' + $this.attr("data-type") + '"]').each(function(i,v){
if($(v).val().length != 0){
var thisVal = mush($(v).val());
var fieldVal = mush($this.val());
var fieldLen = fieldVal.length;
var diff = intersection_destructive(fieldVal, thisVal);
console.log(diff.length/fieldLen);
return acceptable < (diff.length/fieldLen);
}
});
return true;
}, "Unacceptable similarity to another question or answer.");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment