Solved

JQuery addMethod validation

Posted on 2014-04-06
8
481 Views
Last Modified: 2014-04-19
Hi, i am trying to add a new addMethod in jquery validation Plugin so validate the two textfields containing comma separated values must be same

like if textfield1 has 6 values, textfield2 must have 6 values too.

Here is what i have tried so far, but it seems wrong

$.validator.addMethod("sametosame", 
function(value,element) {
    var thing1 = $(element).val().length;
    var thing2 = $(element).val().length; 
    if (thing1 == thing2) {
        return true;
    }
    else {
        return false;
    } 
},'Contents must have same length');

Open in new window

0
Comment
Question by:myselfrandhawa
8 Comments
 
LVL 75

Assisted Solution

by:Michel Plungjan
Michel Plungjan earned 200 total points
ID: 39982464
You pass one element. You need to get the other elements too.

Please note that this test will be irritating if it is executed on each field as it is filled in.

Try (not tested)

$.validator.addMethod("sametosame", 
  function(value,element) {
    var thisID = element.id;
    var thisPrefix = thisID.replace(/\d*$/, ""); // get "textfield"
    var lengths = $("input[name^='thisPrefix']").map(function() { // get all textfield*'s length
      return this.value.length;
     }).get().join(); // into an array
    // find the smallest and largest length
    var min = Math.min.apply(null, lengths),max = Math.max.apply(null, lengths);
    return (min === max);
},'Contents must have same length');

Open in new window

0
 
LVL 15

Author Comment

by:myselfrandhawa
ID: 39982524
Thanks @mplungjan

I will test it and let you know of the same
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 39982609
Typo

 var lengths = $("input[name^='thisPrefix']")

should be

 var lengths = $("input[name^='"+thisPrefix+"']")

assuming the fields you test really do have

xxx1, xxx2, xxx3 as pattern
0
 
LVL 25

Expert Comment

by:Kyle Hamilton
ID: 39982757
instead of splitting and joining the strings, which in theory is expensive, you could just count the number of spaces


var numSpaces = function(text) { 
   var result = text.match(/\s+/g).length;
   return result ? result : 0;
}

Open in new window



you may want to  change the expression to not count begging of line or end of line spaces.
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 39982773
I am not splitting strings.

But I think I have a join() that should not be there


}).get(); // into an array
0
 
LVL 42

Accepted Solution

by:
Rob Jurd, EE MVE earned 300 total points
ID: 39984726
Correct me if I'm wrong but aren't you just wanting to know if both textfields have the same number of values, rather than the same length?

eg.

If textfield1 has 44,2,6,1,111,8 (6 values) and textfield2 has 1,2,3,4,5,6 (also 6 values) then the validation is true?

Here is what I mean:
http://jsbin.com/noqoc/1/edit?js,output

$(document).ready(function() {

  $.validator.addMethod("sametosame", function(value,element) {
    var tmp = value.split(",").length;
    var rtn = true;
    $(".same").each(function(index) {
      console.log($(this).val().split(',').length);
      rtn = rtn && ($(this).val().split(',').length === tmp);
    });
    console.log(rtn);
    return rtn;
  },'Contents must have same length');

  $.validator.addClassRules("same", { sametosame: true });
  $("#test").validate();


});

Open in new window

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 39985434
Hmm, my validation tests that the lenght of what has been typed is the same.

I agree we need elaboration on what exactly you are testing - example data would be useful
0
 
LVL 15

Author Closing Comment

by:myselfrandhawa
ID: 40010335
Thanks Guys
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Introduction A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer …
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now