Date Condition and Validation

Asked

Viewed 164 times

0

I have 3 fields: contract number, start date and end date.

How do I validate two fields simultaneously? That is, the start date and end date must be filled in. If they are not, I have to send only ONE message (and not two, as I am used to doing - one for each field).

To submit this form, it is sufficient that either the contract number or the dates are filled in. There is no need to fill in the two.

1 answer

0


I think you solve it this way, with ifs cascading:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script language="javascript" type="text/javascript">
function emitir(){
    var numero = document.forms["formEmitir"].numero.value;
    var dataini = document.forms["formEmitir"].dataini.value;
    var datafim = document.forms["formEmitir"].datafim.value;
    if(!numero && !dataini && !datafim){
        alert("Preencha com o número do contrato ou as datas!");
    } else {
        if(numero && (dataini || datafim)){
            alert("Preencha apenas o número OU as datas!");
        } else if(numero) {
            alert("Será emitido através do número do contrato...");
        } else if(dataini && datafim){
            alert("Será emitido através das datas...");
        } else {
            alert("Preencha ambas as datas de início e fim!");
        }
    }
}
</script>
</head>

<body>
<form name="formEmitir">
<fieldset>
    <legend>Seu Contrato</legend>
    <p>Pelo número: <input type="text" name="numero" /></p>
    <p>Pela data: de <input type="text" name="dataini" /> a <input type="text" name="datafim" /></p>
    <p><button onclick="emitir();">Emitir</button></p>
</fieldset>
</form>
</body>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.