tags:

views:

255

answers:

3

Hi.
I have 'n' numbers in a TEXTAREA on a form. After the user enters some value in the TEXTAREA, I need to validate it's not a duplicate of any other value.

Ex :

TEXTAREA_1 value =
10
20
30
40
10

It should alert and say 'value 10 was entered more than once'. Please help me with the Javascript.

Thank you so much.

A: 

pure DOM/JS solution:

  <form id="foo">
    <textarea id="numbers-textfield" cols=40 rows=20>10
    20
    30
    40
    50
    60
    60</textarea>
    <br>
    <input type=submit value=submit>
</form>
<script>
    (function() {
    var form = document.getElementById('foo'),
        textarea = document.getElementById('numbers-textfield'),
        inArray = function( value, arr ) {
     for ( var i = arr.length; i--; ) {
         if ( value == arr[i] ) {
      return true;
         }
     }
     return false;
        }


    form.onsubmit = function() {
        var value = textarea.value.split(/\s+/), len = value.length, stack = [], errors = false;


        for ( var i = 0; i<len; ++i ) {
     var isNum = !isNaN( value[i] );
     if ( !isNum ) { continue; }
     if ( errors ) { break; }
     if ( !inArray( value[i], stack ) ) {
         stack.push( value[i] );
     } else {
         errors = true;
         alert( value[i] + ' already in stack');
     }
        }

        if ( errors ) {
     return false;
        }

    }

    })();
</script>
meder
@anon: Why the downvote? Because of the jQuery?
meder
I think, downvote, because it is not solution of this task.
Anatoliy
Exactly. This will not work! Simple as that.
Josh Stodola
oh, I just misunderstood the question. Give me a min then.
meder
updated with full html example.
meder
hai Meder, thank for your answering, i have the answer from Anatoly. thank you very much.
Firdi
A: 
$(function() {
  $("form").submit(function() {
    var txt = $("#TEXTAREA_1");
    var vals = txt.val().split("\n");
    var len = vals.length;

    for(var i = 0; i < len; i++) {
      for(var j = i + 1; j < len; j++) {
        if(vals[i] === vals[j]) {
          alert("Duplicate values are not allowed");
          txt.select();
          return false;
        }
      }
    }
  });
});

It works

Josh Stodola
Hai Josh, thank you for your answering, i have the answer from Anatoly. thank you very much...
Firdi
You're welcome! I've actually had to do this before. This could be easily changed to not use jQuery, too.
Josh Stodola
+1  A: 
var nums = textarea.value.split('\n').sort();
var prev;
for (var i = 0; i < nums.length; i++ ) {
    if (prev && nums[i] == prev) {
        alert('value ' + prev + ' was entered more than once');
        break;
    }
    prev = nums[i];
}
Anatoliy
Hai Anatoliy, your answer is right for me, now my script for this scipt has complete. thank you very-very much...
Firdi
+1 leveraging sort. However note this is purely string-based, it doesn't do numerical comparison so '0' is a different thing to '00' or '0.0'.
bobince