Home > database >  How do I fix this simple regex test?
How do I fix this simple regex test?

Time:02-22

I'm new to all this - all I want to do is use onblur to check first and last names. It may be a basic issue, but I can't seem to figure out why it always spits out the ELSE statement and never the IF. I've tried changing the re1 in many ways, but it doesn't seem to fix it.

function validateFirst () {
    var fName = document.getElementById("firstName").value;
    var re1= /^[a-zA-Z ,.'-] {2,}$/;

    if (re1.test(fName)) {
        document.getElementById ("firstNamePrompt").style.color = "green";
        document.getElementById ("firstNamePrompt").innerHTML = "<strong>valid</strong>";
        return true;
    }
    else {
        document.getElementById ("firstNamePrompt").style.color = "red";
        document.getElementById ("firstNamePrompt").innerHTML = "<strong>Enter 2-15 characters</strong>";
        return false;
    }
}

In my html, I have it written as such :

    <tr>
        <td >First Name</td>
        <td ><input name="firstName" id="firstName" type="text" onblur="validateFirst();"> </td>
        <td ><span id="firstNamePrompt">&nbsp;</span></td>
   </tr>

I may be missing something simple, but any help for this beginner would be greatly appreciated!

CodePudding user response:

Your pattern needs the string to end with a space, so it wont match unless there's a space at the end of fName.

Try this pattern, which meets your requirement of the username only having letters of both cases, spaces, commas, apostrophes, hyphens, periods, and having a minimum of 2 and maximum of 15 characters:

^[a-zA-Z ,.'-]{2,15}$
  • Related