Message for user in Label with Jquery

1

I am doing validation of the registered user's email, and I want to display the message to him in case the email already exists, so I did this:

    //validação de email
    $(function validateEmail() {
        $('#Email').change(function () {
            var url = '@Url.Action("ValidateEmail", "Ajax")';//url do controller que passará a informação
            var email = $('#Email').val();
            $.ajax({
                type: 'POST',
                url: url,
                data: { email: email },
                dataType: 'json',
                success: function (data) {
                    $('#MensagemEmail').append("Email Já Cadastrado");
                    $('#Email').focus();
                },
                error: function (data) {
                    $('#MensagemEmail').append("Email Disponível");
                }
            });
        });
    });//Fim da validação de email

My problem is that when the user enters 2 emails he already has, the message is duplicated as shown in the image below:

My question is how do I clear the value before inserting another one? because I tried to use $('#MensagemEmail').val(''); but it did not roll.

    
asked by anonymous 18.12.2016 / 15:22

2 answers

1

jQuery val () is for data entry only. In your case, since it is a label there are several forms, such as html () or text () :

$('#MensagemEmail').html('');
$('#MensagemEmail').text('');

There is a empty () function that also cleans up the elements as well as cleans the texts.

    
18.12.2016 / 18:02
0

Hello, have you considered using the Jquery validate plugin? This work is much simpler with him.

Here's an example:

    $("#validaEmail").validate({
            rules: { 
                email: {
                    required: true,
                    email: true,
                    remote: {
                        url: "<c:url value='/'/>login/email",
                        type: "get",
                        data: {
                            email: function() {
                                return $("#email").val();
                            }
                        }
                    }   
                }
            },
            messages: {
                email: {
                    required: "Email é obrigatório",
                    remote: "Já existe uma conta associada a este email"
                }
            },
            submitHandler: function(form) {
                form.submit();
            }
        });

Using the remote you pass the url that will check if the email already exists. Your method only has to return a true or false and the defined message will be displayed.

    
18.12.2016 / 15:45