I'm trying to make a from with success message after js validation is correct. For success message I'm using bootstrap alert. I made two files, first one with common validation, where I put all validation functions and second with one function which checked if valid is true. There I tried make a condition if valid is true, then make success message appears, but it's not working. What kind of condition should I use to make it appears?
Form
<!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">
<script src="js/validationCommon.js"></script>
<script src="js/validationMovieForm.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA 058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<title>Movie Form</title>
</head>
<body>
<div id="info" >
<div >
<button type="button" data-dismiss="alert" aria-hidden="true">×</button>
Success! You've added movie.
</div>
</div>
<main>
<form novalidate onsubmit="return validateForm();">
<label for="movieName">Movie name: *</label>
<input type="text" name="movieName" id="movieName" placeholder="2-60 letters"/>
<span id="errorMovieName" ></span>
<label for="Date">Year of release: *</label>
<input type="number" name="premiere" id="premiere" placeholder=" from 1888 to 2021" />
<span id="errorPremiere" ></span>
<label for="Type">Type: *</label>
<input type="text" name="type" id="type" placeholder="2-30 letters"/>
<span id="errorType" ></span>
<label for="Price">Price/week: *</label>
<input type="number" name="price" id="price" placeholder="Price from 1.00 to 49.99"/>
<span id="errorPrice" ></span>
<div >
<p id="errorsSummary" ></p>
<button id="subbut" type="submit" style="margin-right: 4rem;">Add</button>
</div>
</form>
</main>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5 76PVCmYl" crossorigin="anonymous"></script>
<!-- <script>
$(document).ready(function(){
$('.subbut').click(function(){
$('.info').show()
})
});
</script> -->
</body>
</html>
Style
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.form{
margin: 50px;
display: block;
width: 300px;
}
.form select,
.form input[type="text"],
.form input[type="number"] {
border: 1px solid #000;
color: #000;
border-radius: 5px;
padding: 0.5rem;
width: 100%;
}
.form label {
display: block;
margin-bottom: 0.5em;
-ms-grid-column: 1;
-ms-grid-column-span: 1;
grid-column: 1/2;
}
.form input.error-input,
.form select.error-input {
border: 3px solid #e74c3c;
}
.error-text {
display: block;
font-size: .85em;
line-height: 1rem;
margin-left: 10px;
color: #e74c3c;
}
.info {
display: none;
}
validationCommon.js
function resetErrors(inputs, errorTexts, errorInfo) {
for(let i=0; i<inputs.length; i ) {
inputs[i].classList.remove("error-input");
}
for(let i=0; i<errorTexts.length; i ) {
errorTexts[i].innerText = "";
}
errorInfo.innerText = "";
}
function checkRequired(value) {
if (!value) {
return false;
}
value = value.toString().trim();
if (value === "") {
return false;
}
return true;
}
function checkTextLengthRange(value, min, max) {
if (!value) {
return false;
}
value = value.toString().trim();
const length = value.length;
if (max && length > max) {
return false;
}
if (min && length < min) {
return false;
}
return true;
}
function checkYearBetween(value){
if (!value) {
return false;
}
value = value.toString().trim();
const regx = /^\s*(188[8-9]|18[2-9]\d|19\d\d|200\d|201[0-9]|202[0-1])\s*$/;
return regx.test(value);
}
function checkPriceRange(value) {
if (!value) {
return false;
}
value = value.toString().trim();
const regx = /^\s*(([1-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]) \.\d{1,2})\s*$/;
return regx.test(value);
}
validationMovieForm.js
function validateForm() {
const form = document.querySelector('form');
const message = document.getElementById('info');
const movieNameInput = document.getElementById('movieName');
const premiereInput = document.getElementById('premiere');
const typeInput = document.getElementById('type');
const priceInput = document.getElementById('price');
const errorMovieName = document.getElementById('errorMovieName');
const errorPremiere = document.getElementById('errorPremiere');
const errorType = document.getElementById('errorType');
const errorPrice = document.getElementById('errorPrice');
const errorsSummary = document.getElementById('errorsSummary');
let valid = true;
resetErrors([movieNameInput, premiereInput, typeInput, priceInput], [errorMovieName, errorPremiere, errorType, errorPrice], errorsSummary);
if (!checkRequired(movieNameInput.value)) {
valid = false;
movieNameInput.classList.add("error-input");
errorMovieName.innerText = "This field is required";
} else if (!checkTextLengthRange(movieNameInput.value, 2, 60)) {
valid = false;
movieNameInput.classList.add("error-input");
errorMovieName.innerText = "You should enter from 2 to 60 letters";
}
if (!checkYearBetween(premiereInput.value)) {
valid = false;
premiereInput.classList.add("error-input");
errorPremiere.innerText = "This field should be number from 1888 to 2021";
}
if (!checkRequired(typeInput.value)) {
valid = false;
typeInput.classList.add("error-input");
errorType.innerText = "This field is required";
} else if (!checkTextLengthRange(typeInput.value, 2, 30)) {
valid = false;
typeInput.classList.add("error-input");
errorType.innerText = "You should enter from 2 to 30 letters";
}
if (!checkPriceRange(priceInput.value)) {
valid = false;
priceInput.classList.add("error-input");
errorPrice.innerText = "Price must be a number from 1.00 to 49.99";
}
if(valid){
form.addEventListener('submit', (e) =>{
e.preventDefault();
message.classList.add('show');
});
}
if (!valid) {
errorsSummary.innerText = "Form contains errors";
}
return valid;
}
CodePudding user response:
Add css to the success text using js:
show:
/* element */ .style.display = 'block';
hide:
/* element */ .style.display = 'none';
CodePudding user response:
- Instead of manually setting the
.info
div todisplay:none;
in CSS, just use the bootstrap class.d-none
. - On successful validation, instead of adding a
.show
class, just remove the.d-none
class. - On a successful validation, you're adding a new event handler, which means that the form would hve to be submitted a second time for any of that new code to run. So, just remove the additional event handler.
- Finally, your form is going to submit which will cause the page to reload when there is a successful validation (since you're returning
valid
, which will be true). This means that your info div won't be displayed anyway. You need to return false to prevent the form from actually submitting.
// validationCommon.js
function resetErrors(inputs, errorTexts, errorInfo) {
for (let i = 0; i < inputs.length; i ) {
inputs[i].classList.remove("error-input");
}
for (let i = 0; i < errorTexts.length; i ) {
errorTexts[i].innerText = "";
}
errorInfo.innerText = "";
}
function checkRequired(value) {
if (!value) {
return false;
}
value = value.toString().trim();
if (value === "") {
return false;
}
return true;
}
function checkTextLengthRange(value, min, max) {
if (!value) {
return false;
}
value = value.toString().trim();
const length = value.length;
if (max && length > max) {
return false;
}
if (min && length < min) {
return false;
}
return true;
}
function checkYearBetween(value) {
if (!value) {
return false;
}
value = value.toString().trim();
const regx = /^\s*(188[8-9]|18[2-9]\d|19\d\d|200\d|201[0-9]|202[0-1])\s*$/;
return regx.test(value);
}
function checkPriceRange(value) {
if (!value) {
return false;
}
value = value.toString().trim();
const regx = /^\s*(([1-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]) \.\d{1,2})\s*$/;
return regx.test(value);
}
// validationMovieForm.js
function validateForm() {
const form = document.querySelector('form');
const message = document.getElementById('info');
const movieNameInput = document.getElementById('movieName');
const premiereInput = document.getElementById('premiere');
const typeInput = document.getElementById('type');
const priceInput = document.getElementById('price');
const errorMovieName = document.getElementById('errorMovieName');
const errorPremiere = document.getElementById('errorPremiere');
const errorType = document.getElementById('errorType');
const errorPrice = document.getElementById('errorPrice');
const errorsSummary = document.getElementById('errorsSummary');
let valid = true;
resetErrors([movieNameInput, premiereInput, typeInput, priceInput], [errorMovieName, errorPremiere, errorType, errorPrice], errorsSummary);
if (!checkRequired(movieNameInput.value)) {
valid = false;
movieNameInput.classList.add("error-input");
errorMovieName.innerText = "This field is required";
} else if (!checkTextLengthRange(movieNameInput.value, 2, 60)) {
valid = false;
movieNameInput.classList.add("error-input");
errorMovieName.innerText = "You should enter from 2 to 60 letters";
}
if (!checkYearBetween(premiereInput.value)) {
valid = false;
premiereInput.classList.add("error-input");
errorPremiere.innerText = "This field should be number from 1888 to 2021";
}
if (!checkRequired(typeInput.value)) {
valid = false;
typeInput.classList.add("error-input");
errorType.innerText = "This field is required";
} else if (!checkTextLengthRange(typeInput.value, 2, 30)) {
valid = false;
typeInput.classList.add("error-input");
errorType.innerText = "You should enter from 2 to 30 letters";
}
if (!checkPriceRange(priceInput.value)) {
valid = false;
priceInput.classList.add("error-input");
errorPrice.innerText = "Price must be a number from 1.00 to 49.99";
}
if (valid) {
message.classList.remove('d-none');
}
if (!valid) {
errorsSummary.innerText = "Form contains errors";
}
// return valid;
return false;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.form {
margin: 50px;
display: block;
width: 300px;
}
.form select,
.form input[type="text"],
.form input[type="number"] {
border: 1px solid #000;
color: #000;
border-radius: 5px;
padding: 0.5rem;
width: 100%;
}
.form label {
display: block;
margin-bottom: 0.5em;
-ms-grid-column: 1;
-ms-grid-column-span: 1;
grid-column: 1/2;
}
.form input.error-input,
.form select.error-input {
border: 3px solid #e74c3c;
}
.error-text {
display: block;
font-size: .85em;
line-height: 1rem;
margin-left: 10px;
color: #e74c3c;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA 058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700;900&display=swap" rel="stylesheet">
<div id="info" >
<div >
<button type="button" data-dismiss="alert" aria-hidden="true">×</button> Success! You've added movie.
</div>
</div>
<main>
<form novalidate onsubmit="return validateForm();">
<label for="movieName">Movie name: *</label>
<input type="text" name="movieName" id="movieName" placeholder="2-60 letters" />
<span id="errorMovieName" ></span>
<label for="Date">Year of release: *</label>
<input type="number" name="premiere" id="premiere" placeholder=" from 1888 to 2021" />
<span id="errorPremiere" ></span>
<label for="Type">Type: *</label>
<input type="text" name="type" id="type" placeholder="2-30 letters" />
<span id="errorType" ></span>
<label for="Price">Price/week: *</label>
<input type="number" name="price" id="price" placeholder="Price from 1.00 to 49.99" />
<span id="errorPrice" ></span>
<div >
<p id="errorsSummary" ></p>
<button id="subbut" type="submit" style="margin-right: 4rem;">Add</button>
</div>
</form>
</main>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5 76PVCmYl" crossorigin="anonymous"></script>