How to disable the ZIP code mask to save only the numbers entered when making a Post - Asp.net MVC

I'm using a Remark component that has a data-plugin="formatter" in which it applies a zip mask to field. The field has a size of 8 characters, but with the mask it gets 9 because of the "-" (Ex: 29780-000). When saved the record JavaScript Validation performs validation on the client side and does not let the post give because of the amount of characters.

insert the description of the image here

ViewModel:

[DisplayName("CEP")]
[Required(ErrorMessage = "O campo CEP é obrigatório")]
[MaxLength(8, ErrorMessage = "O campo {0} deve ter no máximo {1} caracteres")]
public string CEP { get; set; }

View:

<div class="col-md-2">
    <label asp-for="PessoaFisicaViewModel.PessoasFisicasEnderecosViewModel[i].CEP" class="control-label lb-cep">CEP</label>
    <input type="text" asp-for="PessoaFisicaViewModel.PessoasFisicasEnderecosViewModel[i].CEP" data-plugin="formatter" data-pattern="[[99999]]-[[999]]" class="form-control txt-cep" />
    <span asp-validation-for="PessoaFisicaViewModel.PessoasFisicasEnderecosViewModel[i].CEP" class="text-danger validation-cep"></span>
</div>

Is there any configuration or way of making only the numbers be sent when giving post? In Desktop applications have how to configure for the mask not to be written, but in app web I do not know if it has how. Does anyone know how to help me?

Big hug!!! :)

Author: Albertt Santos, 2018-12-12

1 answers

As you want to keep the dash, instead of changing its mask to data-pattern="[[99999999]]" Change the MaxLength of the field.

[MaxLength(9, ErrorMessage = "O campo {0} deve ter no máximo {1} caracteres")]

And in your backend you can treat these fields by removing the " - " like this:

CEP.Trim('-');

Javascript

Another option that might be valid for you is to use JavaScript and before submitting the form remove the character:

$("form").submit(function(){
   var cepApenasNum = $("#campoCEP").val().replace('-', '');
   $("#campoCEP").val(cepApenasNum);
   alert("Meu cep enviado no form é: " + $("#campoCEP").val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<form action="#">
  <input type="text" id="campoCEP"/>
  <input type="submit" value="Enviar">
</form> 
 1
Author: George Wurthmann, 2018-12-13 10:30:58