The form below has two fields. Validation on this form requires that one field be all numbers and the other is all letters. It does not matter which is which.
When you click the submit button, validation looks at each character in field1 to see if any non-numbers exist. It then checks field1 to see if any non-letters exist. In order to pass validation, only 1 of those two tests must be true.
Next, the page validates field2 the same as it did field 1.
The function has two tests that it considers valid. The first test is if field1 is all numbers and field 2 is all letters. The second test is if field1 is all letters and field2 is all numbers.
If either of the two tests are true, then the data in the form must be valid.
Oh yeah, just for kicks, I also double check to make sure you didn't leave a field blank as a separate error message.
<form name="form1" method="post" action="">
Field 1: <input type="text" id="field1" name="textfield">
<br/>Field 2:<input type="text" id="field2" name="textfield">
<br/><a href="javascript:Validator();">Submit</a>
</form>
<script language="javascript" type="text/javascript">
function Validator(){
var field1IsAllNumbers = true;
var field1IsAllLetters = true;
var field2IsAllNumbers = true;
var field2IsAllLetters = true;
var temp;
var blankValue = false;
if (document.form1.field1.value.length > 0) {
for (i=0; i < document.form1.field1.value.length; i++){
temp = document.form1.field1.value.charAt(i);
if(/[^0-9]/.test(temp)){
var field1IsAllNumbers = false;
}
if(/[^A-Za-z]/.test(temp)){
var field1IsAllLetters = false;
}
}
}
else{
alert('Please enter a value for field 1');
blankValue = true;
}
if (document.form1.field2.value.length > 0) {
for (i=0; i < document.form1.field2.value.length; i++){
temp = document.form1.field2.value.charAt(i);
if(/[^0-9]/.test(temp)){
var field2IsAllNumbers = false;
}
if(/[^A-Za-z]/.test(temp)){
var field2IsAllLetters = false;
}
}
}
else{
alert('Please enter a value for field 2');
blankValue = true;
}
var test1 = field1IsAllNumbers && field2IsAllLetters;
var test2 = field1IsAllLetters && field2IsAllNumbers;
if (!(blankValue) && ((test1) || (test2))){
alert('Valid');
//document.forms['form1'].submit();
}
else{
alert('Invalid');
}
}
</script>