Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8581665
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T21:06:28+00:00 2026-06-11T21:06:28+00:00

I am an MVC C# newbie. I have a project which is using the

  • 0

I am an MVC C# newbie.

I have a project which is using the built-in simple membership features of .net. I have that all working fine. I do however want to prevent a user from choosing certain usernames when registering which are NOT in the database already, such as swear words (of which I have been using plenty today).

I want to test against this list both in an ajax call and on submit. What is the proper way of going about this? I already have the system checking for usernames in use from the DB with no problem.

I have added a list called ReservedWords to the RegisterModel, but I just do not know where or how even to populate it so that it is available to the 2 controllers (async and post).

The Model looks like this:

public class RegisterModel
{
    public string Email { get; set; }

    public string UserName { get; set; }

    public string Password { get; set; }

    public List<ReservedWord> ReservedWords { get; set; }
}

Am I supposed to populate it in the model file or in the controller? In either case can you please provide a sample?

The controller code is here for both the async and post backs:

 // POST: /Account/doesUserNameExist async

    [AllowAnonymous]
    [HttpPost]
    public JsonResult doesUserNameExist(string UserName)
    {
        var user = Membership.GetUser(UserName);
        return Json(user == null);
    }


 // POST: /Account/Register

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                Roles.AddUserToRole(model.UserName, Request.Form["RoleName"]);
                WebSecurity.Login(model.UserName, model.Password);

                return RedirectToAction("Index", "Home");
            }
            catch (MembershipCreateUserException e)
            {
                ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

Thanks in advance!!!!!


Update

So I followed the advice to create a custom validation attribute and it works great on submit. Thanks! Is there a way to get it to work with the client side validation? I have a similar custom validation attribute which compares two fields and makes sure they’re not equal. I followed that code but no luck. Here is the code now:

public class BlackListWordAttribute : ValidationAttribute, IClientValidatable
{
    private const string defaultErrorMessage = "{0} cannot use forbidden word.";

    private readonly List<string> blackListedWords = new List<string>();

    public BlackListWordAttribute()
        : base(defaultErrorMessage)
    {
        //populate from database or text file with cache dependency on either
        blackListedWords.Add("bananas");
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(ErrorMessageString, name);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            if (blackListedWords.Any(x => x.ToLower() == value.ToString().ToLower()))
            {
                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
            }
        }

        return ValidationResult.Success;
    }
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = FormatErrorMessage(metadata.DisplayName),
            //This is the name of the method added to the jQuery validator method (must be lower case)
            ValidationType = "blacklistword"
        };

    }
}

Thanks again!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T21:06:29+00:00Added an answer on June 11, 2026 at 9:06 pm

    I would at using custom validation. If you change your mode to

    public class RegisterModel
    {
        public string Email { get; set; }
    
        [BlackListWord]
        public string UserName { get; set; }
    
        public string Password { get; set; }
    }
    

    Then the custom validation attribute could look something like:

        [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
        public class BlackListWordValidationAttribute : ValidationAttribute {
            private readonly List<string>  blackListedWords = new List<string>();
    
            public BlackListWordValidationAttribute() {
                //populate from database or text file with cache dependency on either
                blackListedWords.Add("bananas");
            }
            protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
                if(value!=null) {
                    if (blackListedWords.Any(x => x.ToLower() == value.ToString().ToLower()))
                        return new ValidationResult(@"Cannot use black listed word.");
                }
    
                return ValidationResult.Success;
            }
        }
    

    You can store the blacklist either in the database or a file or xml or whatever.

    Then you can add client side validation as well. To help with that look at using something like this Filthy List which you can access via a web service.

    EDIT/UPDATE No 2:

    As requested by the question asker. The best way to make the code available to both “async and post backs” is to create a string extension method. For instance,

    public static class StringExtension {
            public static bool IsUserNameAllowed(this string value) {
        List<ReservedWord> ReservedWords = GetReservedWordsFromPersistantMedium();
    
        return ReservedWords.All(x => x.Word.ToLower() != value.ToLower());
        }
    } 
    

    The above class to be put either a referenced project or extensions folder with web project.

    Then you can just call

    model.UserName.IsUserNameAllowed() or userName.IsUserNameAllowed()
    

    For example:

    [AllowAnonymous]
    [HttpPost]
    public JsonResult doesUserNameExist(string UserName)
    {
        if !(UserName.IsUserNameAllowed())
        {
            return Json(new { ErrorMessage="An error has occured"});
        }
        var user = Membership.GetUser(UserName);
        return Json(user == null);
    }
    

    in either scenarios

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Hey all, this is a newbie ASP.NET MVC question. I have a view that
Newbie question. I’m writing an ASP.Net MVC app in VB.Net and have been using
I need to make a simple asp.net MVC project, which contains a GridView. I
I am newbie with asp.net MVC and i want something simple. I have an
I'm a newbie about ASP.NET MVC 3, but I have a simple question. Is
I have an ASP.NET MVC project in C# using Forms Authentication and Active Directory
MVC newbie question re binders. Supposing I have two strongly typed partial actions that
I'm an asp.net newbie. I have inherited a base of asp.net mvc code and
Yet another newbie with ASP.NET MVC! All I intend to do is for a
I'm a newbie to all this ASP.NET MVC stuff, and I was making some

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.