Anna wrote:
I have a form with a few text boxes which need to be validated client-side.
The validation is: check that every single text box has a unique string value.
You could iterate through each input text whose value should be unique
and log the results into an object: when a property has already been
defined, this means you have a duplicate.
<form onsubmit="return v(this)">
<input type="text" name="n1_UNIQUE" title="player 1"><br>
<input type="text" name="n2_UNIQUE" title="player 2"><br>
<input type="text" name="n3_UNIQUE" title="player 3"><br>
<input type="text" name="n4_UNIQUE" title="player 4"><br>
<input type="text" name="n5"><br>
<input type="submit">
</form>
<script type="text/javascript">
function v(frm){
var h={}, ii, el=frm.elements, val, err=[], index=1;
function p(s){err.push((index++)+" - "+s);}
function c(fld, bErr){fld.style.backgroundColor=bErr?"#c00":"";}
for(ii=0; ii<el.length; ii++){
if(el[ii].type && el[ii].type.toLowerCase()=="text"){
if(el[ii].name.indexOf("UNIQUE")!=-1){
//we're in a field whose value should be unique
val=el[ii].value.toLowerCase(); //case-insensitive
if(typeof h[val] != "undefined") {
// that's a duplicate, log an error
p("The field "+el[ii].title+" is a duplicate!");
c(el[ii], true);
}else{
// first time encoutered
h[val] = true;
c(el[ii], false);
}}}}
return err.length==0 || (alert(err.join("\n")), false);
}
</script>
HTH
Yep.