Reputation: 1
I'm trying to validate the Firstname and the Surname fields in an HTML document via JavaScript. The validation has to prompt whether the user inserted a valid Name/Surname meaning that no numbers or weird characters should be in the input box.
I've been searching stackoverflow and other similar websites for a solution but unfortunately I didn't find the exact solution I was looking for so I'm hoping that someone around this website can give a helping hand.
This is my HTML code:
<form name="contact" method="post" action="contact.php">
<table width="200" border="0" align="center">
<tr>
<td><p class="pagetext">Name:</p></td>
<td><input type="text" name="fname" id="fname" size="30"/></td>
</tr>
<tr>
<td><p class="pagetext">Surname:</p></td>
<td><input type="text" name="sname" id="sname" size="30"/></td>
</tr>
<tr>
<td><p class="pagetext">Email:</p></td>
<td><input type="text" name="email" id="email" size="30"/></td>
</tr>
<tr>
<td><input class="btns" type="submit" onclick="validationMain();validationContact();validationErrors();" value="Submit"/></td>
<td><input class="btns" type="submit" onclick="validationReset()" value="Reset"/></td>
</tr>
</table>
</form>
This is the JavaScript Code (left out the irrelevant parts so as not to clutter the question):
var errors = "";
var textOnly = /^[A-Za-z]+$/;
function validationMain(){
var firstname = document.getElementById('fname');
var surname = document.getElementById('sname');
var email = document.getElementById('email');
//emailRegEx expression from www.regular-expressions.info/email.html
var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (firstname.value == "") {
errors += "First Name Cannot Be Left Empty\r\n";
} else {
if (firstname.value != textOnly.value){
errors += "First Name is Invalid\r\n";
}
}
if (surname.value == "") {
errors += "Surname Cannot Be Left Empty\r\n";
} else {
if (surname.value != textOnly.value){
errors += "Surname is Invalid\r\n";
}
}
if (email.value != ""){
if (email.value.search(emailRegEx) == -1){
errors += "Invalid Email Entered\r\n";
}
} else {
errors += "Email Cannot Be Left Empty\r\n";
}
}
The main problem is that whatever Names or Surnames I input in the text field (even if they are correct ones without numbers and special characters) It will prompt that they are invalid (which shouldn't be the case) so I'm guessing there is something wrong with my if condition.
Thank you in advance for your time, help and any relative information provided :)
I hope I gave enough information, if not please let me know!
Upvotes: 0
Views: 916
Reputation: 75
The following line is comparing the value from the text field to a property value of the regular expression.
if (firstname.value != textOnly.value){
You need to test the value with the regexp to see if it's valid.
Upvotes: 0
Reputation: 2683
You aren't using your expressions right.
textOnly.test(firstname.value);
test
checks if the expression would match.
Upvotes: 2