I have an input from user for his first name
I wanna immediate check the values he enter if it's less than 4 I will create a div that holds him the error
also I wanna check if the input has any numbers I will create a div also to tell him that he shouldn't enter a digit in his name
so this is my Html Code first
<div> <label> <span> First Name: </span> <input type="text" name="FirstName" id = "myInput" onkeyup="myFunction()" placeholder="Enter your First Name..." /> </label> </div>
and this is my java Script Function
function is_number(input) {
if(input === '')
return false;
let regex = new RegExp(/[^0-9]/, 'g');
return (input.match(regex) === null);
}
function myFunction() {
const x = document.getElementById("myInput").value;
for(let i = 0; i <= x.length; i++) {
if (x.length < 4){
document.getElementById("demo").innerHTML = "You Enterd less Than 4 Numbers"
}
else if(is_number(x)) {
document.getElementById("demo").innerHTML = "First Name Should Not Have Digits in it"
}
else {
document.getElementById("demo").style.display = "none";
}
}
}
Use this to sanitize the input:
function isValid(input) {
let regex = /[A-Z]/i;
if(!regex.test(input)) {
document.getElementById("demo").innerHTML = "First name should not have digits in it"
}
if(input.length < 4) {
document.getElementById("demo").innerHTML = "You entered less than 4 characters"
}
}
The /[A-Z]/ pattern only matches alphabet characters and the i flag ignores the characters case.
The pattern matches both the empty strings and numbers. It also matches characters like ' when followed preced by a alphabet character, so names like "O'brien" are fine.