Razor form field validation

1

I'm using MVC5 Razor to create my forms, now I have a question for the validations of the fields of this form;

Example:

    @Html.LabelFor(m => m.Nome, "Nome:")
    @Html.DropDownListFor(m => m.Nome, "Nenhum" , new { @class = "form-dropdown" } )

    @Html.CheckboxFor(m => m.IsObrigaInfoCidade, new { @class = "form-checkbox" });
    @Html.LabelFor(m => m.IsObrigaInfoCidade, "Obrigar Informar a Cidade")

    @Html.LabelFor(m => m.Cidade, "Cidade")
    @Html.DropDownListFor(m => m.Cidade, "Nenhum" , new { @class = "form-dropdown" } )

Validations:

- Quando m => m.ID for igual a 0(zero), então o enabled = true, caso contratio enabled = false;
- Quando o chequebox IsObrigaInfoCidade estiver selecionado o campo CIDADE deve ficar disabed = false,
caso contrário a cidade deve ficar enabled = true;

I believe that I have to do the field validation for the field with Javascript and Jquery, however I do not know how to do it or is it the best way to do this? and if the user disable the page javascript? Thank you for your attention!

    
asked by anonymous 26.10.2017 / 14:36

2 answers

1

As stated in your question, if you already have the value of the ID, just make a comparison in Razor itself to decide how the field will be displayed:

@if (Model.ID == 0)
{ 
    @Html.LabelFor(m => m.Nome, "Nome:")
    @Html.DropDownListFor(m => m.Nome, "Nenhum" , new { @class = "form-dropdown" } )

    @Html.CheckboxFor(m => m.IsObrigaInfoCidade, new { @class = "form-checkbox" });
    @Html.LabelFor(m => m.IsObrigaInfoCidade, "Obrigar Informar a Cidade")

    @Html.LabelFor(m => m.Cidade, "Cidade")
    @Html.DropDownListFor(m => m.Cidade, "Nenhum" , new { @class = "form-dropdown" } )
}
else
{
    @Html.LabelFor(m => m.Nome, "Nome:")
    @Html.DropDownListFor(m => m.Nome, "Nenhum" , new { @class = "form-dropdown", @disabled = "disabled" } )

    @Html.CheckboxFor(m => m.IsObrigaInfoCidade, new { @class = "form-checkbox", @disabled = "disabled" });
    @Html.LabelFor(m => m.IsObrigaInfoCidade, "Obrigar Informar a Cidade")

    @Html.LabelFor(m => m.Cidade, "Cidade")
    @Html.DropDownListFor(m => m.Cidade, "Nenhum" , new { @class = "form-dropdown", @disabled = "disabled" } )
}

Already for the condition of the checkbox, you need to do in your JS:

 $('#IsObrigaInfoCidade').on('click', function() {
    if ($(this).is(':checked')) {
        $('#Cidade').prop('disabled', 'disabled');
    } else {
        $('#Cidade').removeAttr('disabled');
    }
 });
    
26.10.2017 / 14:58
1

Good morning.

You can actually do it via Javascript and Jquery, the user can disable the java script, in this scenario, I believe you are using some template class in your MVC, the best way is to use the dataannotations directly in the class in question: see an example: above each property of the class are the notes about the property and one of them is informed that the information is required [System.ComponentModel.DataAnnotations.Required (ErrorMessage="Fill in the Name" field]] for this use the namespaces System.componentModel and System.componentModel.DataAnnotations.

In this way even if the user disables Javascript, when the request arrives on the server the information will not be validated.

using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations;

Namespace Project.Domain.Entities {     public class Client     {         [Key]         public int ClientId {get; set; } // Table ID

    [System.ComponentModel.DataAnnotations.Required(ErrorMessage = "Preencha o campo Nome")]
    [MaxLength(150, ErrorMessage = "Máximo de 150 caracteres")]
    [MinLength(2, ErrorMessage = "Minimo de 2 caracteres")]
    public string Nome { get; set; } // Nome do cliente

    using System.Collections.Generic;

using System.ComponentModel; using System.ComponentModel.DataAnnotations;

namespace ProjectModelDDD.Domain.Entities {     public class Client     {         [Key]         public int ClientId {get; set; }

    [System.ComponentModel.DataAnnotations.Required(ErrorMessage = "Preencha o campo Nome")]
    [MaxLength(150, ErrorMessage = "Máximo de 150 caracteres")]
    [MinLength(2, ErrorMessage = "Minimo de 2 caracteres")]
    public string Nome { get; set; }

    [System.ComponentModel.DataAnnotations.Required(ErrorMessage = "Preencha o campo Sobrenome")]
    [MaxLength(150, ErrorMessage = "Máximo de 150 caracteres")]
    [MinLength(2, ErrorMessage = "Minimo de 2 caracteres")]
    public string Sobrenome { get; set; }

    [System.ComponentModel.DataAnnotations.Required(ErrorMessage = "Preencha o campo Email")]
    [MaxLength(150, ErrorMessage = "Máximo de 150 caracteres")]
    [EmailAddress(ErrorMessage = "Preencha um e-mail válido")]
    [DisplayName("E-mail")]
    public string Email { get; set; }

    [DataType(DataType.Date)]
    public DateTime DataCadastro { get; set; }
    public bool Ativo { get; set; }

    public virtual IEnumerable<Produto> Produtos { get; set; }

    public bool ClienteEspecial(Cliente cliente)
    {
        return cliente.Ativo && DateTime.Now.Year - cliente.DataCadastro.Year >= 5;
    }
}

} [System.ComponentModel.DataAnnotations.Required (ErrorMessage="Fill in the LastName field")]         [MaxLength (150, ErrorMessage="150 characters maximum")]         [MinLength (2, ErrorMessage="Minimum of 2 characters")]         public string LastName {get; set; } // Client surname

    [System.ComponentModel.DataAnnotations.Required(ErrorMessage = "Preencha o campo Email")]
    [MaxLength(150, ErrorMessage = "Máximo de 150 caracteres")]
    [EmailAddress(ErrorMessage = "Preencha um e-mail válido")]
    [DisplayName("E-mail")]
    public string Email { get; set; } //Email do cliente

    [DataType(DataType.Date)]
    public DateTime DataCadastro { get; set; }
    public bool Ativo { get; set; } // Checa se o cliente está ativo

    public virtual IEnumerable<Produto> Produtos { get; set; }

}

}

    
26.10.2017 / 15:19