How to call a Javascript Function inside a Razor?

Asked

Viewed 1,898 times

-1

I am programming in ASP.NET MVC and I have a registration form. I need to check if the date of birth is valid, ie if it is less than today’s date. I have the script but do not know how to call it within the form down, someone could 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 took 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();
    }
}
  • This is simple...just change the Submit button to a link (element a) and with a function that picks up the click, captures the informed date, call your function is after a manual Submit...tomorrow I will be well wrapped...I do not know if I can send you an example but the day after tomorrow you cover me I send

3 answers

0

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

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

0

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

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

0

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

@Html.EditorFor(model => model.DataNascimento,  new { htmlAttributes = new { @class = "form-control", @onchange = "verificaData()" } })

Browser other questions tagged

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