Validate field after typing in ASP.NET MVC

Asked

Viewed 1,531 times

3

I have a registration page in ASP.NET MVC with Entity Framework, this registration has an indication field, where the nickname of the user that indicated.

I wanted after typing this field by the user to validate in the ASP.NET controller with the Entity if it exists, if it does not display the invalid nickname message.

You would have something of ASP.NET MVC + Entity to do this or you would need to do it with jquery and ajax, and how to do it?

3 answers

3


You can use Partial View of ASP.Net MVC and Jquery Ajax.

In your Controller create a method that returns a Partialview:

    public PartialViewResult CheckNickname(string nickname)
    {
        if (Nicknames.GetNicknames().Exists(x => x == nickname))
            ViewBag.StatusNickName = "Nickname existe";
        else
            ViewBag.StatusNickName = "Nickname não existe";

        return PartialView();
    }

Right-click on the Checknickname method and click "add view". When you open the View settings window check the box "Create as partial view".

inserir a descrição da imagem aqui

In your Partial View you can put the nickname validation message, I used a Viewbag to return the message (only this code below in partial view):

<h1>@Html.ViewBag.StatusNickName</h1>

Now you need to render Partial View somewhere in your Registration View:

<div id="checkNicknameDiv">
@{
    Html.RenderPartial("CheckNickname");
}

This is the Ajax that will call the method that returns the partial view:

<script type="text/javascript">

function checkNickname() {
    $.ajax(
    {
        type: 'GET',
        url: '/User/CheckNickname',
        data: { nickname: $('#nickname').val() },
        dataType: 'html',
        cache: false,
        async: true,
        success: function (data) {
            $('#checkNicknameDiv').html(data);
        }
    });
}</script>

In the parameter data ajax put the code that will catch the value of the indication field.

To trigger the function checkNickname(), I created a timer. When starting to type in the field, the timer waits a second without typing to trigger the function, if you continue typing before completing a second, the timer is reset and starts again.

    var typingTimer;                //timer
    var doneTypingInterval = 1000;  //tempo ms, 1 segundo por exemplo
    var $input = $('#nickname'); //campo de indicação

    //no keyup, cria o contador e começa a contagem
    $input.on('keyup', function () {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    });

    //no keydown, elimina o contador
    $input.on('keydown', function (e) {
        var keyCode = e.keyCode || e.which;
        //se teclar tab
        if (keyCode == 9) {
            checkNickname();
        }
        else {
            clearTimeout(typingTimer);
        }        
    });

    //se o tempo acabar, chama a função
    function doneTyping() {
        checkNickname();
    }

Any questions are just talk...!

  • Filipe thank you so much for your reply, it was exactly what I wanted, it worked correctly and helped me understand the functioning of ASP.NET + Ajax. Note: The only thing is that the timer does not work if you type and TAB to jump line.

  • You’re welcome @Alisson! Thanks for the feedback, I changed the javascript to trigger the function if you type tab, check it out. Taking advantage, if everything is right, click on the check to accept the answer...big hug!

  • Thanks Filipe, only left me one last doubt... Hj my model contains the id_sponsor and in the view the controls are being done on top of an input where the user informs the sponsor nickname. I could put the validation in the Model with Modelstate.Addmodelerror and after validation update in the Model the ID_PATROCINADOR? Thanks in advance for the help and attention.

2

You can put the following attribute in the username field template

[Remote("validaExiste", "Account", HttpMethod = "POST", ErrorMessage = "User name already exists. Please enter a different user name.")]
public string Username

....

Then creates the method on the controller more or less like this:

[HttpPost]
public JsonResult validaExiste(string UserName) {

    var user = Membership.GetUser(UserName);

    return Json(user == null);
}

Note: it takes jquery.validate.min.js and jquery.validate.unobtrusive.min.js

1

From what I understand you want to check if the value exists in the database. If there is no such value, show a warning.

I prefer to use Ajax.beginForm, easier and cleaner. But you need one more plugin to install.

Follow Nuget: https://www.nuget.org/packages/Microsoft.jQuery.Unobtrusive.Ajax

Follow an example in the view or partialview:

@using (Ajax.BeginForm("Colocar nome da ação", "Colocar controller aqui", new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccess" }, new { @role = "form" }))
{
@Html.AntiForgeryToken()

<div class="form-group">
    <label>Exemplo</label>
    @Html.TextBoxFor(m => m.Exemplo, new { @class = "form-control", @maxlength = "15", @placeholder = "Digite o seu nickname", @autocomplete = "off" })
    @Html.ValidationMessageFor(m => m.Exemplo, "", new { @class = "text-danger" })
</div> 

<button type="submit" class="btn btn-success">Submit</button>
}

//JS
<script>
function OnSuccess(responsive) {
     alert(responsive.result);
}
</script>

Controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult NomeDaSuaAção(SeuModel model)
{
    using (var ctx = new Entities())
    {
        var result = ctx.SuaTabela.Where(x => x.SeuCampo == "valor").FirstOrDefault();

        if (result == null)
        {
            return Json(new { result = true }, JsonRequestBehavior.AllowGet);
        }
    }
}
  • Matheus, in your case it would only validate after clicking the Ubmit button, correct ?

  • @Alissonmarqui, after Ubmit, will go in the controller, check etc... and send warning

Browser other questions tagged

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