Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What did I do wrong here? [Javascript Regex]

So I am writing a registration form and I need the display name to be only numbers, letters and underscores.

Have a look at my code and tell me what I'm doing wrong.

<form method="post" action="/" onsubmit="return check_form()">
    <input type="text" id="display-name" name="display-name" maxlength="255" />
    <input type="submit" />
</form>
<script type="text/javascript">
<!--
    var name_regex = /^([a-zA-Z0-9_])+/

    function check_form()
    {
        if (!name_regex.test(document.forms[0].elements[0].value))
        {
            document.forms[0].elements[0].focus()
            alert("Your display name may only contain letters, numbers and underscores")
            return false
        }
    }
-->
</script>

It's obviously been trimmed down to not include anything not related to the problem but even this snippet doesn't work.

like image 548
Andrew G. Johnson Avatar asked Nov 30 '22 13:11

Andrew G. Johnson


1 Answers

Your regex

/^([a-zA-Z0-9_])+/

Looks for

  1. Start of string(check), followed by
  2. 1 or more letters, numbers, or underscore (check)

And then whatever comes after it doesn't matter. This regex will match anything at all so long as it begins with a letter, number, or underscore

If you put a $ at the end, then it will work - $ matches 'end of string', so the only way it can match is if there are only numbers, letters, and underscores between the start and end of the string.

/^([a-zA-Z0-9_])+$/

Secondly, I'd suggest using document.getElementById('display-name').value instead of document.forms as it won't break if you rearrange the HTML, and is more 'the commonly accepted standard of what to do'

like image 200
Orion Edwards Avatar answered Dec 09 '22 23:12

Orion Edwards