Reputation: 147
I am having trouble with the gender check. No matter what I do it always registers true unless I only have it check for one condition. IE: If I enter m or f it does not register. But if I write a condition only checking for the letter m it will work.
function Validate()
{
var name= document.getElementById('name').value;
var age= document.getElementById('age').value;
var sex= document.getElementById('sex').value;
var error ="";
var check = 0;
if(name=="")
{
check=1;
error= error +" Please enter a valid name \n";
}
if(age>100 || age<1)
{
check=1;
error= error +" Please enter a valid age \n";
}
if(sex != "f" || sex !="m")
{
check=1;
error= error +" Please enter a valid sex \n";
}
if (check>0)
{
alert(error);
check=0;
return false;
}
}
HTML:
<form action="cartoon.html" method="post" onsubmit="return Validate()">
<br>
Name
<input type="text" placeholder="last name" id="name"/>
<input type="text" placeholder="first name" id="name"/>
<input type="text" placeholder="middle initial"/>
</br>
<br>
Age
<input type="number" placeholder="Age" id="age"/>
</br>
<br>
sex
<input type="text" placeholder="Sex" id="sex"/>
</br>
<input type="submit" value="login"/>
</form>
Upvotes: 0
Views: 75
Reputation: 925
More complex variant
if (!(sex == 'm' || sex == 'f')) {
check = 1;
error= error + " Please enter a valid sex \n";
}
Upvotes: 0
Reputation: 1041
if(sex != "f" || sex !="m"){
check=1;
error= error +" Please enter a valid sex \n";
}
If sex is F first part is false but second is true because sex is not M -> statement is true -> error
Same goes for M input.
you need to make this change:
if(sex != "f" && sex !="m"){
check=1;
error= error +" Please enter a valid sex \n";
}
It is a boolean logic error
Upvotes: 0