Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC username availability check

I have read a lot of step by step tutorials and still couldn't get my code to work, I went through the solutions on this site with no luck either, i don't know what i am doing wrong.

I am using jQuery and want to find out whether the username "mark" is taken or not, I haven't even reached the database linkage yet.

[HTML]

<input id="user_name" name="user_name" onchange="UserCheck()" type="text" value="" />
<div id="status" />

[JS]

function UserCheck() {
    $("#status").html("Checking....");
    $.post("/user/check",
    { username: $("#user_name").val() },
    function (data) {
        if (data == 0) {
            $("#status").html("Available");
        }
        else {
            $("#status").html("Taken");
        }
    });
}


[Controller]

public JsonResult check(FormCollection form)
{
    System.Threading.Thread.Sleep(3000);
    string name = form["username"];

    if (name.Equals("mark")){
        return Json(1);
    } else {
        return Json(0);
    }
}
like image 653
Cindro Avatar asked Nov 20 '11 08:11

Cindro


2 Answers

Check the below link out :

Check Instantly If Username Exists - ASP.NET MVC Remote Validation

What you need here is RemoteAttribute for the property your are checking and also you need to implement a controller action which returns JsonResult with Boolean value.

Here is a brief sample:

Your model:

    [Required]
    [Display(Name = "User name")]
    [Remote("doesUserNameExist", "Account", HttpMethod = "POST", ErrorMessage = "User name already exists. Please enter a different user name.")]
    public string UserName { get; set; } 

Your action result:

[HttpPost]
public JsonResult doesUserNameExist(string UserName) {

    var user = Membership.GetUser(UserName);

    return Json(user == null);
}

You can tweak the business logic inside the action result for your needs.

Also, make sure that you have the following libraries referenced on your registration page along with your jQuery file:

jquery.validate.min.js

jquery.validate.unobtrusive.min.js

The above blog post covers everything you need.

NOTE

Keep it in mind that Remote validation does not kick in on the server side. You might wanna check the below link out for server side remote validation (I don't recommend using it on production though, it is full of holes but it will give you an idea):

http://www.tugberkugurlu.com/archive/asp-net-mvc-server-side-remote-validation

like image 73
tugberk Avatar answered Oct 07 '22 00:10

tugberk


See my full article on this topic. How to: Implement Remote Validation in ASP.NET MVC

like image 29
RickAndMSFT Avatar answered Oct 07 '22 00:10

RickAndMSFT