Forum Moderators: open
function formValidator2(){
valid = true;
if ((document.getElementById('secondphone').value != '' ) && (document.getElementById('secondphone').value.length <= 7 )){
alert ( "Test." );
valid = false;
}
return valid;
}
function formValidator2(){
valid = true;
var numExpsecphone = /^[0-9]+$/;
if ((document.getElementById('secondphone').value != '' ) && (document.getElementById('secondphone').value.length <= 7 ) && (document.getElementById('secondphone').value.match(numExpsecphone))){
alert ( "Test." );
valid = false;
}
return valid;
}
function formValidator2(){
var valid = false,
secondphone = document.getElementById('secondphone'),
numExpsecphone = /^[0-9]+$/;
if ((secondphone.value.length >= 7 ) && (numExpsecphone.test(secondphone.value))){
alert ( "Test." );
valid = true;
}
return valid;
}
1. You probably want a "var" in front of "valid"
2. You can make this more efficient by storing the result of document.getElementById('secondphone') in a variable instead of calling getElementById over and over.
3. Try using RegExp.test instead of match.
4. I think you are testing for a valid secondphone, in which case I think your tests may be slightly incorrect. I would assume you want to verify:
A) The string is not empty
B) The string is AT LEAST 7 characters in length (you have this wrong)
C) The string contains only digits
However, the first test (string not empty) is redundant, as both the second and third conditions would handle that case, so I would get rid of the first check.
Isn't this supposed to work either way?
I want to make sure the field is numeric and has a length restriction only if the person typed something in the field, the can leave it blank if they choose as it is the second phone number.
function formValidator2(){
var valid = false,
secondphone = document.getElementById('secondphone'),
numExpsecphone = /^[0-9]+$/;
if (secondphone.value.length == 0) {
valid = true;
}
else if ((secondphone.value.length >= 8 ) && (numExpsecphone.test(secondphone.value))){
valid = true;
}
alert("Returning " + valid);
return valid;
}
[edited by: Fotiman at 7:27 pm (utc) on Sep 30, 2010]
function formValidator2(){
var valid = true,
secondphone = document.getElementById('secondphone'),
numExpsecphone = /^[0-9]+$/;
if (secondphone.value.length == 0) {
//valid = true;
}
else if ((secondphone.value.length >= 8 ) && (numExpsecphone.test(secondphone.value))){
//valid = true;
}
else {
// The phone number is not blank, it's length is < 8 or not numeric
valid = false;
}
alert("Returning " + valid);
return valid;
}
function formValidator2(){
var valid = true,
secondphone = document.getElementById('secondphone'),
numExpsecphone = /^[0-9]+$/;
if (secondphone.value.length != 0) {
if ((secondphone.value.length < 8 ) || (!numExpsecphone.test(secondphone.value))){
// The phone number is not blank, it's length is < 8 or not numeric
valid = false;
}
}
alert("Returning " + valid);
return valid;
}