Limit character entry in EditFor in MVC

1

I have a character limiter for just TEXT. Now I need the characters to be limited to only 2 (I want to make the user type the state, for example: PR, SP, RJ ...). How do I do it?

    $(document).ready(function () {
        $(".apenastexto").keypress(function (event) {
            var inputValue = event.which;                    
            if (!(inputValue >= 65 && inputValue <= 233) && (inputValue != 32 && inputValue != 0)) {
                event.preventDefault();
            }

        });
        $(".apenastexto").addClass("form-control");
    });
    
asked by anonymous 18.05.2017 / 02:23

2 answers

1

You can configure this in your ViewModel using Data Annotation:

[StringLength(2, ErrorMessage = "É necessário informar 2 caracteres para a Unidade Federativa.", MinimumLength = 2)]
public string Uf { get; set; }

Or use a javascript function enabled in the save button click:     // HTML

<button type="button" value="Salvar" onclick="incluiValor(this);">

function incluiValor(sender) {
if ($('#txtUf').val().length < 2 || $('#txtUf').val().length > 2 ) {
    // alerta o usuário, adiciona uma classe css de erro.
    return false;
} 
    
18.05.2017 / 02:51
1

Answering the question

Well, I think you'd better use the maxlength attribute of a TextBoxFor instead of EditorFor .

EditorFor has no overhead for this.

Dai just add this to your View:

@Html.TextBoxFor(model => model.uf, new {maxlength = 2})

Best Solution in my opinion

For me, you'd better use a DropDownList.

Dai just add this to your controller:

 List<SelectListItem> uf = new List<SelectListItem>();

 items.Add(new SelectListItem { Text = "Goiás", Value = "GO"});

 items.Add(new SelectListItem { Text = "São Paulo", Value = "SP" });

 items.Add(new SelectListItem { Text = "Rio de Janeiro", Value = "RJ", Selected = true });

 ViewBag.uf = uf;

 return View();

And here's your View:

@Html.DropDownList("uf")

You can also create a table with states, and instead of popular in the "hand", just instantiate the class and send it to the view.     

18.05.2017 / 20:24