How to call a JavaScript function inside a Razor?

-1

I'm programming in ASP.NET MVC and I have a registration form. I need to verify that the date of birth is valid, that is, if it is shorter than today's date. I have the script but I do not know how to call it inside the form below, could anyone help me?

<div class="form-group">    
  <label><span class="req"></span> Data de Nascimento</label>    
   @Html.EditorFor(model => model.DataNascimento,  new { htmlAttributes = new { @class = "form-control" } })
   @Html.ValidationMessageFor(model => model.DataNascimento, "", new { @class = "text-danger" })    
</div>             

I got this script from another response to implement:

function verificaData() 
{
    var dt = new Date();
    var dia = dt.getDay();
    var mes = dt.getMonth();
    var ano = dt.getFullYear();

    if(dia > 0 && dia < 10) dia = "0" + dia;
    if(mes > 0 && mes < 10) mes = "0" + mes;

    var dataAtual = dia + "/" + mes + "/" + ano;
    var vDia = document.model.DataNascimento.value.substr(0,2);
    var vMes = document.model.DataNascimento.value.substr(3, 2);
    var vAno = document.model.DataNascimento.value.substr(6, 5);

    if(vDia > dia ||
       vMes > mes ||
       vAno > ano) 
    {
        alert("Data Inválida");
        document.model.DataNascimento.value = dataAtual;
        document.model.DataNascimento.focus();
    }
}
    
asked by anonymous 17.10.2016 / 00:36

3 answers

0

Your form will be sent to the Controller when the user submits.

There, you can call your function to validate the date and, if it is wrong, return to form with an error message.

    
17.10.2016 / 17:04
0

Add to the onchange attribute of your element the verificaData() function

@Html.EditorFor(model => model.DataNascimento,  new { htmlAttributes = new { @class = "form-control", @onchange = "verificaData()" } })
    
17.10.2016 / 23:28
0

The best event to check the date is the field output, made by onblur : / p>

@Html.EditorFor(model => model.DataNascimento,  new { htmlAttributes = new { @class = "form-control", @onblur = "verificaData()" } })
    
09.11.2016 / 21:17