Validation of fields from Razor forms

Asked

Viewed 655 times

1

I’m using MVC5 Razor to create my forms, now I have a question for field validations of that 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 I have to do field pro validation with Javascript and Jquery, but I don’t know how to do it or if it is the best way to do it? what if the user disables the javascript of the page? Thanks for your attention!

  • It depends, you already have the "m.ID" in the page render or it is a value changed by the screen/filled by the user?

  • I already have the value of the ID, but the Isobrigainfocidade will be changed on the screen!

2 answers

1


As stated in your question, if you already have the ID value, 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');
    }
 });
  • @IF worked well, but is still giving problem when clicking the checkbox: Uncaught ReferenceError: $ is not defined

  • Apparently your jquery is not instantiated on the page.. check this out

1

Good morning.

You can really do via Javascript and Jquery, the user can yes disable the java script, in this scenario, I believe that you are using some model class in your MVC, the best way is to use the dataannotations directly in the class in question: see an example: above each class property are annotations 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.

This way even if the user disables Javascript, when the request reaches the server the information will not be validated.

using System.Collections.Generic; using System.Componentmodel; Using system.ComponentModel.Dataannotations;

namespace Projeto.domain.Entities { public class Client { [Key] public int Clienteid { get; set; } //ID of table

    [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 Projetomodeloddd.domain.Entities { public class Client { [Key] public int Clienteid { 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 Last name field")] [Maxlength(150, Errormessage = "Maximum 150 characters")] [Minlength(2, Errormessage = "Minimum 2 characters")] public string Last name { get; set; } //Last name of client

    [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; }

}

}

Browser other questions tagged

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