Validate date in editfor

Asked

Viewed 54 times

0

I made a date mask and would like to know, how I validate the date right there, IE, already in Edit he does not accept date like: 23/16/9087. This is my date editfor

<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", @id = "nascimento" } })
            @Html.ValidationMessageFor(model => model.dataNascimento, "", new { @class = "text-danger" })
        </div>
    </div>

In the model I display a date requirement message (if it is empty), but if it is an invalid date it passes anyway and I do not want to play this rule to the bank.

How I value?

public class Funcionario
    {
        [Key]
        public int id { get; set; }
        [Required(ErrorMessage ="Nome do funcionário é obrigatório", AllowEmptyStrings =false)]
        [Display(Name ="Nome")]
        public String nome { get; set; }
        [Required(ErrorMessage = "Data de Nascimento do funcionário é obrigatório", AllowEmptyStrings = false)]
        [Display(Name = "Data de Nascimento")]
        public String dataNascimento { get; set; }
        [Required(ErrorMessage = "CPF do funcionário é obrigatório", AllowEmptyStrings = false)]
        [Display(Name = "CPF")]
        public String cpf { get; set; }
        [Display(Name ="Nome da Cidade")]
        public String NomeCidade { get; set; } 
        [Required(ErrorMessage = "Cidade do funcionário é obrigatório", AllowEmptyStrings = false)]
        [Display(Name = "Cidade")]
        public virtual int cidade { get; set; }
    }
  • post your model

  • @Leandroangelo, I posted the model

  • If it’s a Data field, why did you use string instead of Datetime?

  • If you are going to keep it this way you will have to do the validation by Regex

  • What do you mean, @Leandroangelo. What do I have to do?

  • First, The date of birth should be type Date from the database and so reflect on your Entity and Viewmodel

  • It is that when passing the date, it only accepts in the format yyyy-mm-dd and if I give a Convert in the database to display in our format, I cannot insert. I switched to Datetime

  • No man, you’re doing it wrong, The bank will save the date in the format of it, As you will display is another stop with Sistem.Globalization

  • I know, I’ve fixed it too. Now I’ve put all Datetime and the mask works

Show 5 more comments

1 answer

1

Use the attribute System.ComponentModel.Dataannotations.Rangeattribute.

Example:

[Range(typeof(DataTime), "01/01/2001", "01/01/2020", ErrorMessage = "Data Inválida")]
public DateTime Data { get; set; }

Browser other questions tagged

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