开发者

Javascript : To check if the fields in a form are not identical

开发者 https://www.devze.com 2022-12-11 14:46 出处:网络
I have the following problem. The following is the form i have <input type=\"text\" name=\"email1\" />

I have the following problem.

The following is the form i have

<input type="text" name="email1" />
<input type="text" name="email2" />
<input type="text" name="email3" />
<input type="text" name="email4"开发者_如何学C />
<input type="text" name="email5" />

I want all the 5 Email ids to be different (unique) i.e, i dont want the user to be entering the same Email IDs in all the fields.

I need this to be done in Javscript

Can someone please help me with this

Thanks,

Kartik


for (var i = 1; i < 6; i++) {
    for (var j = i+1; j < 6; j++) {
        if (document.getElementsByName("email"+i)[0].value ==
            document.getElementsByName("email"+j)[0].value) {
            alert("Fields "+i+" and "+j+" are equal!");
        }
    }
}

You may want to add another check, if you allow several of the fields to stay empty.


In Javascript an Array can act as a stack (push/pop) in which you can push new items after checking they're not already in the stack.

var emailAddrs = [];
var item;

    for(var i = 0; i < 5; i++){
      item = document.getElementsByName("email"+i)[0].value;
      if(! emailAddrs.contains(item))
        emailAddrs.push(item);
    }

UPDATE

Once you have your array build, you can then use that as a basis to do other operations. Using the length property of the array, you can check how many items are in the array vs how many you expected to see.

You could also push identical items into another array and use this information to let the user know what needs changing

UPDATE 2

I just realised that the contains method I use is created by adding the following code:

Array.prototype.contains = function(obj) {
  var i = this.length;
  while (i--) {
    if (this[i] === obj) {
      return true;
    }
  }
  return false;
}

This then creates a contains method to each array object.

If you're using jQuery, you can also do $.inArray(value, array)

0

精彩评论

暂无评论...
验证码 换一张
取 消