Message to the user in Label with Jquery

Asked

Viewed 393 times

1

I’m validating the registered user’s email, and I want to display the message to him if the email already exists, so I did so:

    //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 inserts 2 emails that already have, the message is duplicated as shown in the image below:

inserir a descrição da imagem aqui

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

2 answers

1


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

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

There is the function Empty() also, that in addition to cleaning the elements also cleans the texts.

  • 1

    Thank you @lucascosta

0

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

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

Browser other questions tagged

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