How to validate an input?
I have a form that sends the values entered in the input
to another page. I want to make a validation between the inputs, if one number is greater than another, and if it is not, do not go to the second page and warn with a alert
.
This is my HTML Code:
<form action="_graphes.php" method="post">
<input type="time" id="time_debut" name="time_debut" step="1" value=''>
<input type="time" id="time_fin" name="time_fin" step="1" value='' >
<input id=btn type=submit name=go value=ok>
</form>
Is a javascript:
if(document.getElementById("time_debut").value > document.getElementById("time_fin").value){
alert("Maior");
}
3 answers
You can validate the form by following the example below, by supplementing I put the validation to check if one or both fields are empty:
Html
<form action="_graphes.php" method="post" id="formulario">
<input type="time" id="time_debut" name="time_debut" step="1" value="">
<input type="time" id="time_fin" name="time_fin" step="1" value="" >
<input id="btn" type="button" onclick="return envia()" name="go" value="ok">
</form>
The input
'btn' when clicked it calls the function envia()
below, where the validation and sending of the form
takes place.
Js
function envia() {
var time_debut = document.getElementById("time_debut").value;
var time_fin = document.getElementById("time_fin").value;
if(time_debut == '' || time_fin == '') {
alert("Preencha todos os campos!");
}
else if (time_debut > time_fin){
alert("Maior");
}
else {
document.getElementById("formulario").submit();
}
}
Js (without validating if Fields are empty)
function envia() {
var time_debut = document.getElementById("time_debut").value;
var time_fin = document.getElementById("time_fin").value;
if (time_debut > time_fin){
alert("Maior");
}
else {
document.getElementById("formulario").submit();
}
}
Try to do by putting submit only in javascript.
This is your HTML:
<form id="frm" action="_graphes.php" method="post">
<input type="time" id="time_debut" name="time_debut" step="1" value=''>
<input type="time" id="time_fin" name="time_fin" step="1" value='' >
<input id="btn" type="button" onclick="javascript: btn_click()" name="go" value="ok">
</form>
Is a javascript:
function btn_click() {
if (document.getElementById("time_debut").value > document.getElementById("time_fin").value) {
alert("Maior");
return;
}
document.getElementById("frm").submit();
}
In the form
tag, add a call to the form validation function.
<form action="_graphes.php" method="post" onsubmit="validar()">
The validation function will contain the code snippet you have already built:
function validar() {
if(document.getElementById("time_debut").value > document.getElementById("time_fin").value) {
alert("Maior");
return (false);
}
else {
return (true);
}
}
return(false)
will cause the submission of the form to stop, and the next page will not be called.