JSFiddle - React, Tailwind, and code Playground
by ananyaneogi
HTML
<form id="userForm">
<input type="text" name="name" id="name" placeholder="Name">
<span class="error"></span>
<input type="email" name="email" id="email" placeholder="Email">
<span></span>
<input type="number" name="phone" id="phone" placeholder="Phone">
<span></span>
<button type="submit">Submit</button>
</form>
CSS
span {
display: block;
}
JavaScript
function debounce(fn, delay) {
// maintain a timer
let timer = null;
// closure function that has access to timer
return function() {
// get the scope and parameters of the function
// via 'this' and 'arguments'
let _this = this;
let args = arguments;
// if event is called, clear the timer and start over
clearTimeout(timer);
timer = setTimeout(function() {
fn.apply(_this, args);
}, delay);
}
}
const form = document.getElementById('userForm');
function checkInput(e) {
const currentInput = form[e.target.name];
if (currentInput.value) {
if (currentInput.value.length < 10) {
currentInput.nextElementSibling.innerText = 'oh horror!';
}
if (currentInput.name === 'phone') {
const phoneRgx = /^(\+)?0*(91+)?[- .]*?([5-9][0-9]{9})/;
console.log(phoneRgx.test(currentInput.value), currentInput.value);
if (!phoneRgx.test(currentInput.value)) {
currentInput.nextElementSibling.innerText = 'oh horror';
} else {
currentInput.nextElementSibling.innerText = 'All Good!';
}
}
}
}
/* form.addEventListener('input', debounce(checkInput, 300)); */
const form1 = $("#userForm");
form1.on('input', function(e) {
const currentInput = $(form1).find('#' + [e.target.name]);
console.log(currentInput.val());
if (currentInput.val()) {
console.log(currentInput.val().length);
if (currentInput.val().length < 10) {
console.log(currentInput.closest('span'));
currentInput.next('span').text('oh horror!');
} else {
currentInput.next('span').text('all good!');
}
} else {
currentInput.nextAll('span').empty()
}
console.log(currentInput.nextAll('span'));
})