Created
May 10, 2013 16:57
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.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