Limit Editfor input in MVC

Asked

Viewed 725 times

1

I have a character limiter for TEXT only. Now I need the characters to be limited in only 2 (I want to make the user type the state, for example: PR, SP, RJ...). How 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");
    });

2 answers

1

Answering the question

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

EditorFor 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.

So 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 then in your View:

@Html.DropDownList("uf")

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

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 by clicking the save button: //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;
} 

Browser other questions tagged

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