Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to accept only alphabets as input and not numbers? If numbers are given it should show a validation error as it takes only alphabets

I'm creating a form where I give certain fields. For now, an input field with type text.

I have tried giving validation " required " but that is not what I am searching for. If a user gives a number as input, it should validate that it takes only alphabets.

<form action="/action_page.php">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit" value="Submit">
</form>

Can you help me how can I do this on the go while typing inside the textfield and validate if a number is given

like image 544
rey Avatar asked Mar 04 '23 05:03

rey


1 Answers

You can do validation using pattern like this.

<form action="/action_page.php">
  First name: <input type="text" pattern="[A-Za-z]" name="fname"><br>
  Last name: <input type="text" pattern="[A-Za-z]" name="lname"><br>
  <input type="submit" value="Submit">
</form>

or validation can be done by Jquery. input fields will not accept any other input except alphabets.

<!DOCTYPE html>

        <html lang="en">
            <head>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
            </head>
            <body>
               First name <input type="text" pattern="[A-Za-z]" id="fname" name="fname"><br>
               Last name <input type="text" pattern="[A-Za-z]" id="lname" name="lname"><br>
                <script>
                    $( document ).ready(function() {
                        $( "#fname" ).keypress(function(e) {
                            var key = e.keyCode;
                            if (key >= 48 && key <= 57) {
                                e.preventDefault();
                            }
                        });
                        $( "#lname" ).keypress(function(e) {
                            var key = e.keyCode;
                             if (key >= 48 && key <= 57) {
                                e.preventDefault();
                            }
                         });
                    });
                </script>
            </body>
        </html>
like image 83
Imran Iqbal Avatar answered Apr 08 '23 12:04

Imran Iqbal