Skip to content

Instantly share code, notes, and snippets.

@adarsh-chakraborty
Created October 5, 2021 08:04
Show Gist options
  • Save adarsh-chakraborty/cf6482c10bb8ef78e42ed2a9f1b86858 to your computer and use it in GitHub Desktop.
Save adarsh-chakraborty/cf6482c10bb8ef78e42ed2a9f1b86858 to your computer and use it in GitHub Desktop.
Demo file to demonstrate name validation in html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Validation</title>
</head>
<body>
<input id="fullName" type="text" minlength="4"><button id="btn">Submit</button>
<script>
const btn = document.getElementById('btn');
const fullName = document.getElementById('fullName');
btn.addEventListener('click',() => {
let nameText = fullName.value;
// Check if empty. minimum 4 + 4
if(nameText.trim().length > 8){
let name = nameText.split(' '); // Regex blank space (Spliting by space);
if(name.length === 2){
if(name[0].trim().length >= 4 || name[0].trim().length >= 4){
// Checking if name contains numbers
let letters = /^[A-Za-z]+$/;
if(name[0].match(letters) && name[1].match(letters)){
alert('Congrats, Your name met all the conditions!');
}else{
alert("Only letters are allowed in names. [A-Z] <First Name> <Last Name>");
}
}else{
alert("Minimum 4 characters for each <First Name> <Last Name>");
}
}else{
alert("Invalid syntax, Please enter only <First Name> <Last Name>");
}
}else{
alert("Please enter full name. (Min 4 chars each) <First Name> <Last Name>");
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment