question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Username length validation error

See original GitHub issue

Hi there

Firstly a great job with this framework. I am trying to change the UserName length to 256. I’ve read many posts where it’s suggested to override the UserName StringLength. But for some reason it doesn’t appear to work for me

Your Abp package version. 3.8.0 Your base framework: .Net Framework or .Net Core. .Net Core Exception message and stack trace if available. Your request is not valid! The following errors were detected during validation. - The field UserName must be a string with a maximum length of 32.

Steps needed to reproduce the problem. Download ASP.NET Core 2.0 Multipage version Run the web app

Changed the Username length to 256 in both the User and UserDto classes

public class User : AbpUser<User>
    {
        public const string DefaultPassword = "123qwe";

        // OVERRIDE here
        [StringLength(256)]
        [MaxLength(256)]
        public override string UserName { get; set; }

        public static string CreateRandomPassword()
        {
            return Guid.NewGuid().ToString("N").Truncate(16);
        }

        public static User CreateTenantAdminUser(int tenantId, string emailAddress)
        {
            var user = new User
            {
                TenantId = tenantId,
                UserName = AdminUserName,
                Name = AdminUserName,
                Surname = AdminUserName,
                EmailAddress = emailAddress
            };

            user.SetNormalizedNames();

            return user;
        }
    }

image

No matter what I try the validator still thinks I’m trying to use max length 32, am I overriding in the wrong error?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:36 (15 by maintainers)

github_iconTop GitHub Comments

4reactions
techcolincommented, Jun 14, 2018

Great - that worked! Now managed through the HandleEvent override and the error is gone. Records all created as expected.

For completeness I as you suggested I needed to override the Update handler as follows:

public override void HandleEvent(EntityUpdatedEventData<AbpUserBase> eventData) { using (_unitOfWorkManager.Current.SetTenantId(null)) { UserAccountOverride userAccount = (UserAccountOverride)_userAccountRepository.FirstOrDefault(ua => ua.TenantId == eventData.Entity.TenantId && ua.UserId == eventData.Entity.Id); if (userAccount != null) { userAccount.UserName = eventData.Entity.UserName; userAccount.EmailAddress = eventData.Entity.EmailAddress; userAccount.LastLoginTime = eventData.Entity.LastLoginTime; _userAccountRepository.Update(userAccount); } } }

Thanks very much for your help with this - I don’t think I’d have got there on my own, but I now have some new insight into ABP.

1reaction
ismcagdascommented, Jun 14, 2018

@techcolin yes @ebicoglu is talking about ASP.NET Core version but your’s is ASP.NET MVC 5.x. Workaround below might work for you;

  1. Instead of using modelBuilder.Entity<User>().Property(t => t.UserName).HasMaxLength(50); do it like this;

Add below lines into your User class;

[StringLength(256)]
public override string UserName { get; set; }
  1. Create a user account class like this;
[Table("AbpUserAccounts")]
public class MyUserAccount : UserAccount
{
	[StringLength(256)]
	public override string UserName { get; set; }
}
  1. Change length of UserName field in CreateUserDto class.

  2. Create a new class for UserAccount synchronization;

public class MyUserAccountSynchronizer : UserAccountSynchronizer
{
	private readonly IUnitOfWorkManager _unitOfWorkManager;
	private readonly IRepository<UserAccount, long> _userAccountRepository;

	public MyUserAccountSynchronizer(
		IRepository<UserAccount, long> userAccountRepository, 
		IUnitOfWorkManager unitOfWorkManager) : base(userAccountRepository, unitOfWorkManager)
	{
		_userAccountRepository = userAccountRepository;
		_unitOfWorkManager = unitOfWorkManager;
	}

	public override void HandleEvent(EntityCreatedEventData<AbpUserBase> eventData)
	{
		using (_unitOfWorkManager.Current.SetTenantId(null))
		{
			_userAccountRepository.Insert(new MyUserAccount
			{
				TenantId = eventData.Entity.TenantId,
				UserName = eventData.Entity.UserName,
				UserId = eventData.Entity.Id,
				EmailAddress = eventData.Entity.EmailAddress,
				LastLoginTime = eventData.Entity.LastLoginTime
			});
		}
	}
}
  1. Replace ABP’s UserAccountSynchronizer with your version in the PreInitialize method of your Core module;

Configuration.ReplaceService<UserAccountSynchronizer, MyUserAccountSynchronizer>();

If you have problems while updating a user, you can also override Update event;

public virtual void HandleEvent(EntityUpdatedEventData<AbpUserBase> eventData)
{
    // ....
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

how to validate username minlength and show error ...
Try this if (!validateSignUp(signUpValues)) { setErrors({ ...errors, userNameErr:"Username should be atleast 4 char.
Read more >
How to check username length for form validation? JS
Trying to build a form validation with JavaScript and my mind has gone ... innerText = 'message'; } //checklength of username and password ......
Read more >
How to display reactive validation error on character length?
Solved: Hello, There is a field with 100 character length in CDS Entity. And, in Edit form, the character length validation doesn't display...
Read more >
What should be maximum and minimum length of persons ...
Between 6 and 20 characters for a password is acceptable, although I would normally not restrict the password length quite so tightly at...
Read more >
Registration - validation message on username field
Validation error should be: "Invalid username. Usernames must start with a letter. Allowed characters are a-z (only lower case), 0-9, _, - (dash) ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found