What have I done wrong here? [Javascript Regex]

So, I am writing a registration form, and I need the display name to be only numbers, letters and underscores. Check out 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>

Obviously, this was trimmed so as not to include anything that is not related to the problem, but even this fragment does not work.

+3
source share
9 answers

Your regular expression

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

Looking for

  • Beginning of line (check) followed by
  • 1 or more letters, numbers or underscores (verification)

And then everything that comes after this does not matter. This regular expression will match anything as long as it starts with a letter, number, or underscore

$ , - $ " ", , , - , .

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

-, document.getElementById('display-name').value document.forms, , HTML- " , "

+14

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

edit: , $, - .

+6

" ". , , ( , ).

@Annan, , , $ , , .

0

, ( , , ).

0

" "? ? ? ?

Per @Annan, $, , abc123!@#.

, , , ( JS).

0

script javascript. , :

<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>
0

, , . , , . $ !

0

var name_regex = /^([a-z0-9_])+$/i;
0

:

var name_regex = /^\w+$/;
0

Source: https://habr.com/ru/post/1696470/


All Articles