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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With