JSFiddle - React, Tailwind, and code Playground
HTML
<form class ="form-field" id="form-div">
<label for="comment">Send a comment</label>
<textarea id="commentID" name="comment" autocomplete="off"></textarea>
<small></small>
</form>
JavaScript
const commentValidation = document.querySelectorAll("textarea").value;
const form = document.getElementById("form-div");
const checkComment = () =>{
let valid = false;
const comment = commentValidation;
if(!isRequired(comment)){
showError(commentValidation, "Comment cannot be blank");
}else if(!isCommentValid(comment)){
showError(commentValidation,"comment is not valid")
}else{
showSuccess(commentValidation);
valid = true;
}
return valid;
};
const isCommentValid = (comment) =>{
const re = /[a-zA-Z]/;
return re.test(comment);
};
const showSuccess = (input) =>{
const formField = input.parentElement;
formField.classList.remove('error');
formField.classList.add('success');
const error = formField.querySelector('small');
error.textContent = '';
}
form.addEventListener('submit', function (e){
e.preventDefault();
let isCommentValid = checkComment();
if (isFormValid){
}
});
form.addEventListener('keyup', function (e){
e.preventDefault();
if (e.key === 'Enter' || e.keyCode === 13) {
form.submit();
}
});