JSFiddle - React, Tailwind, and code Playground
by hlim188
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>RegEx Form</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>New User Signup</h1>
<form>
<input type="text" name="username" placeholder="username">
<p>Username must be alphanumeric and contains 5 - 12 characters</p>
<input type="text" name="email" placeholder="email">
<p>Email must be a valid address, e.g. [email protected]</p>
<input type="password" name="password" placeholder="password">
<p>Password must alphanumeric (@, _ and - are also allowed) and be 8 - 20 characters</p>
<input type="text" name="telephone" placeholder="telephone">
<p>Telephone must be a valid UK telephone number (11 digits)</p>
<input type="text" name="slug" placeholder="profile slug">
<p>Slug must contain only lowercase letters, numbers and hyphens and be 8 - 20 characters</p>
</form>
<script type="text/javascript" src="validation.js"></script>
</body>
</html>
CSS
body{
font-family: arial;
color: #333;
}
h1{
font-weight: normal;
margin: 20px auto;
text-align: center;
}
form{
width: 300px;
margin: 20px auto;
}
input{
display: block;
padding: 8px 16px;
font-size: 2em;
margin: 10px auto;
width: 100%;
box-sizing: border-box;
border-radius: 10px;
border: 3px solid #ccc;
outline: none !important;
}
input.valid{
border-color: green;
}
input.invalid{
border-color: orange;
}
input + p {
font-size: 0.9em;
font-weight: bold;
text-align: center;
margin: 0 10px;
color: orange;
opacity: 0;
height: 0;
}
input.invalid + p {
opacity: 1;
height: auto;
margin-bottom: 20px;
}
JavaScript
// validation script here
const inputs = document.querySelectorAll('input');
const patterns = {
telephone: /^\d{11}$/,
username: /^[a-z\d]{5,11}$/i,
password: /^[\w@-]{8,20}$/,
slug: /^[a-z\d-]{8,20}$/,
email: /^([a-z\d\.-]+)@([a-z\d-]+)\.([a-z]{2,8})(\.[a-z]{2,8})?$/
};
// validation function
function validate(field, regex){
// console.log(regex.test(field.value));
if(regex.test(field.value)){
field.className = 'valid';
} else {
field.className = 'invalid';
}
}
inputs.forEach((input) => {
input.addEventListener('keyup',(e) => {
// console.log(e.target.attributes.name.value);
validate(e.target, patterns[e.target.attributes.name.value]);
})
});