Need help with validating the firstname
using regex. The javascript code provided generates an error if the value length is 0, however, even after entering a correct firstname format based on the regex, it still shows 'First name invalid'. I suspect there might be an issue with my else-if block.
Here is the Java Script code:
function validate(){
var valid = true;
var regex="([A-Za-z]{3,30}\s*)";
if (document.getElementById('fname').value.length == 0) {
validationMessage = validationMessage + ' - First name is missing\r\n';
document.getElementById('errorFirstNameMissing').style.visibility='visible';
valid = false;
}
else if(document.getElementById('fname').value!=regex){
validationMessage = validationMessage + ' - First name is not valid can contain only letters from A-z and a-z\r\n';
document.getElementById('errorFirstNameInValid').style.visibility='visible';
valid = false;
}
else{
document.getElementById('errorFirstNameMissing').style.visibility='hidden';
document.getElementById('errorFirstNameInValid').style.visibility='hidden';
}
if (valid == false){
alert(validationMessage);
}
return valid;
}
Here is the JSP code:
<form name="Register" action="RegisterServlet" method="post" onSubmit="return validate()">
<table>
<tr>
<td>First Name* : </td>
<td><input type="text" name="txtFname" id="fname" maxlength="30"/><br/>
<span id="errorFirstNameMissing" style="visibility:hidden;">*Please provide your first
name.</span><br/>
<span id="errorFirstNameInValid" style="visibility:hidden;">*Please provide a valid first
name.</span>
</td>
</tr>