Validate field after typing in ASP.NET MVC

3

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

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

Would there be anything of the ASP.NET MVC + Entity itself to do this or would it need to do with jquery and ajax, and how?

    
asked by anonymous 07.03.2017 / 05:06

3 answers

3

You can use ASP.Net MVC Partial View 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 on "add view". When you open the View settings window check the "Create as partial view" box.

InyourPartialViewyoucanputthevalidationmessageofthenickname,IusedaViewBagtoreturnthemessage(onlyhasthiscodebelowinthepartialview):

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

NowyouneedtorenderPartialViewsomewhereinyourRegistrationView:

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

This is 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 of ajax put the code that will get the value of the indication field.

To trigger the checkNickname() function, I created a timer. When you start typing in the field, the timer waits for a second without typing to trigger the function, if you continue typing before completing one second, the timer will reset and start 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, just talk ... hugs!

    
07.03.2017 / 15:19
2

You can put the following attribute in the username template field

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

....

Then create the method in the controller something like this:

[HttpPost]
public JsonResult validaExiste(string UserName) {

    var user = Membership.GetUser(UserName);

    return Json(user == null);
}

Note: you need jquery.validate.min.js and jquery.validate.unobtrusive.min.js

    
07.03.2017 / 12:05
1

From what I understand you want to check if the value exists in the database. If that value does not exist, show a warning.

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

Follow NuGet: link

Here is 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);
        }
    }
}
    
09.03.2017 / 01:01