Date validation with Jquery

Asked

Viewed 566 times

-1

How to do date validation from Editorfor using jquery? wanted to check if the date typed by the user, and if the date he typed is greater than the current date, display a message to him stating the error

<div class="form-group">
    @Html.LabelFor(model => model.DataNascimento, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.DataNascimento, new { htmlAttributes = new { @class = "form-control data" } })
        @Html.ValidationMessageFor(model => model.DataNascimento, "", new { @class = "text-danger" })
    </div>
</div>

thought to do a jquery that picks up the typed content and checks the date. Someone can help me?

with the help of @Lucasdefreitaskauer this script has been made:

$("#DataDeNascimento").on("blur", validarDataDeNascimento);
var validarDataDeNascimento = function () {
    var dataDeNascimentoStr = $("#DataDeNascimento").val();
    var dataDeNascimento = new Date(dataDeNascimentoStr);
    var agora = new Date();
    if (dataDeNascimento > agora) {
        alert("A data de nascimento não pode ser uma data futura.");
    }
};

and was added to Editorfor the ID id = "Dated" but when you lose Focus(Blur) it shows no warning.

  • What exactly do you want to validate? Could explain your problem better?

  • I edited the question

  • Why did you put "- Pending" in the title of the question?

1 answer

2


First you will need to add one id the field of date of birth:

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

Then you can do the validation as follows:

$("#DataDeNascimento").on("change", validarDataDeNascimento);

var validarDataDeNascimento = function () { 
    var dataDeNascimentoStr = $("#DataDeNascimento").val();
    var dataDeNascimento = new Date(dataDeNascimentoStr);
    var agora = new Date();

    if (dataDeNascimento > agora) {
        alert("A data de nascimento não pode ser uma data futura.");
    }   
};

Updated

Can be done in the onBlur also. To this end, it will be necessary to amend $("#DataDeNascimento").on("change", validarDataDeNascimento); for $("#DataDeNascimento").on("blur", validarDataDeNascimento);

  • if I want to do the validation when he takes out Focus (Blur) as I would?

  • Replace o change by Blur. I’ll change it for you.

  • I tried that, it didn’t work :\

  • can put error?

  • Depending on the format of the date you expect it will not work. It needs to be yyyy-mm-dd

  • Shows no error, the default date is en dd/mm/yyyy

  • That’s probably the problem! Edit your question again by adding more instructions and the JS code you tried to do.

  • edited question

Show 3 more comments

Browser other questions tagged

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