Home>

I want to display red text if the input format is incorrect when I enter the wrong text.
Is the code wrong? If so, how can I check the operation?

<html>
<head>
<meta charset = "utf-8">
<meta robot = "noindex">
<style>
    .error {
        color: red;
    }
</style>
</head>
<body>
    <form name = "form">
        Phone number<input type = "text" name = "tel" value = "" placeholder = "number only 10 to 11 digits
            "Onkeyup =" check ();">
        <p></p>
        <script>
            function check ()
            {
                var error = document.getElementById ('error');
                var telCheck = document.form.tel.value;
                if (telcheck.match (/ [0-9] {10,11}/g)! = telCheck) {
                    error.setAttribute ('class', 'error');
                    error.innerHTML = 'Input format is incorrect';
                } else {
                    error.removeAttribute ('class');
                    error.innerHTML = '';
                }
            }
        </script>
    </form>
</body>
</html>

`` `

  • Answer # 1

    With this condition, JavaScript can be implemented without writing a single character.

    Phone number<input type = "text" name = "tel" value = "" placeholder = "10 to 11 digits only for numbers"
    pattern = "\ d {10,11}">
            <p id = "error">Incorrect input format</p>
    input: valid + # error {
      display: none;
    }

    patternmatches the input and the result can be retrieved as a CSS selector: valid,: invalid.

    Example of making CodePen

  • Answer # 2

    The front of onkeyup is a full-width space and the telCheck c is lowercase.
    When debugging, you should check the developer tools to see if there are any errors.

Related articles