Write to DB without mask applied by jQuery

-1

I'm doing a project in MVC and with the use of jQuery I made the CPF mask as below:

$(document).ready(function()
{
    $(".cpf").mask("999.999.999-99");
    $(".cpf").addClass("form-control");
});

Follow my div :

<div class="form-group">
    @Html.LabelFor(model => model.Cliente_CPF, htmlAttributes: new { @class = "control-label" })
    <div>
        @Html.EditorFor(model => model.Cliente_CPF, new { htmlAttributes = new { @class = "cpf" } })
        @Html.ValidationMessageFor(model => model.Cliente_CPF, "", new { @class = "text-danger" })
    </div>
</div>

The mask is working properly, however I need this information to be written to my DB without the mask! Only CPF numbers.

How should I do it?

    
asked by anonymous 06.05.2017 / 18:17

1 answer

1

I see two options: (1) handle the value on the client side with JavaScript (2) handle the value on the server side with C #. For full warranty, you can implement both ways.

JavaScript

With JavaScript, you can assign a function to the submit event of the form and in this function remove all characters that are not CPF digits.

$(document).ready(function()
{
    $(".cpf").mask("999.999.999-99");
    $(".cpf").addClass("form-control");

    // vvvvv--- Lembre-se de colocar o seletor correto para o seu caso:
    $("#form").submit(function () {
        var cpfValue = $(".cpf").val();

        // Remove os caracteres que não são dígitos:
        cpfValue = cpfValue.replace(/\D/g, '');

       // Atualiza o valor no campo do formulário:
       $(".cpf").val( cpfValue );
    });
});

In this way, the value sent will be numeric only.

C #

This language is not my area but a quick search I saw that you can do something like:

string cpfOnlyDigits = Regex.Replace(cpf, "[^\d]", "");

Then in the database, instead of saving the value of cpf , which would be the value received in the HTTP request, you would save the value of cpfOnlyDigits , the value being filtered, with only digits. >     

06.05.2017 / 18:42