It is a typical HTML form with textboxes. I am looking for the client side validation you get with forms but it’s not happening. I’m sure I did something wrong but I don’t know what it is. I am expecting real time validation on my ‘required’ textbox elements.
Right now I have two buttons, one to open the dialog box and one button to close it.
I’d like to do something with the data being submitted but I need the form validation to happen first so I haven’t written out any logic for that yet.
EDIT: I don’t know if you always had to do this but I added two CSS properties and it did work so, is this how it always needs to be? This is what I added to my CSS file
input:invalid {
border: 2px solid red;
}
input:valid {
border: 2px solid black;
}
const modal = document.querySelector('.modal');
const openModal = document.querySelector('.open-button');
const closeModal = document.querySelector('.close-button');
openModal.addEventListener('click', () => {
modal.showModal();
});
closeModal.addEventListener('click', () => {
modal.close();
})
modal::backdrop {
background: rgb(0 0 0 / .4);
}
.modal {
padding: 1em;
max-width: 50ch;
}
body {
background-color: rgb(215, 137, 28);
}
dialog label {
font-size: 18px;
}
dialog h2 {
margin-top: 10px;
}
dialog text {
width: 100%;
}
dialog input:nth-of-type(3) {
margin-bottom: 20px;
}
.close-button {
margin-bottom: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h2>An interesting title</h2>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Amet maiores placeat dolorum corporis nihil sapiente cupiditate animi rem ab tenetur facilis ad hic corrupti eligendi, nulla labore, impedit eveniet repudiandae!</p>
<button class="button open-button">open modal</button>
<dialog class="modal" id="modal">
<h2>An interesting title</h2>
<form class="form" method="dialog">
<label>Book Title </label><br><input type="text" required /><br>
<label>Author </label><br><input id="author" type="text" required /><br>
<label>Number of pages </label><br><input id="pages" type="text" required /><br>
</form>
<button class="button close-button">close modal</button>
</dialog>
<script type="module" src="index.js"></script>
</body>
</html>
2
Answers
You forgot the submit button.
Look at this post to do it without it.
And the validation occurs when submitting, right now you don’t have the validation because it’s not submitting.
Submitting a form by pressing enter without a submit button
This works for me.
Use these classes on each input to validate.
classes:
not-null: can not be empty.
ranged: length must be between minlength and maxlength.
num-only: value must be numeric.