2

I'm building out a function to allow users to change their email address and if they accidentally put in a whitespace before or after, I need to trim it so the regex doesn't complain. It doesn't seem to work in the place I have it (the string remains exactly the same) but I'm not sure why. This is in my controller:

public ActionResult ChangeEmail(ChangeEmailVM vm)
        {
            try
            {
                if (UserManager.EmailAvail(new EmailRequest
                {
                    Email = vm.EmailAddress.Trim()
                }))
                else//...etc etc

I was thinking I'd possibly need to put .trim() in the getter or setter of the email address but I'm not sure of the proper syntax.

xyzcode
  • 219
  • 1
  • 7
  • 14
  • 4
    Please elaborate about 'not working properly'. What do you expect it to do, and what is it doing? – Rob Nov 25 '15 at 23:07
  • What do you expect this to be doing that it's not? – Preston Guillot Nov 25 '15 at 23:07
  • 2
    Trim will only remove trailing or leading whitespace. If you want to remove all whitespace, use replace. – JD Davis Nov 25 '15 at 23:08
  • This might help http://stackoverflow.com/questions/6219454/efficient-way-to-remove-all-whitespace-from-string – myselfmiqdad Nov 25 '15 at 23:10
  • It doesn't affect the input at all. So if the user enters " xyz@test.com " (with whitespace before and after), it will still leave all of the extra whitespaces – xyzcode Nov 25 '15 at 23:24
  • 1
    Trim doesn't mutate the string. It returns a new string that has been trimmed. You've only passed the trimmed string into `EmailAvailForReg`. `UpdateEmail` is not going to have the trimmed string because the `EmailAddress` property on `viewModel` wasn't changed. – Mike Zboray Nov 25 '15 at 23:27

1 Answers1

7

Keep in mind that string is read only - you cannot change the value by calling anything on it, and instead these methods return new values with the desired changes, including .Trim; if you wish to change viewModel.EmailAddress you should assign the result of Trim() to that same variable:

EDIT: At some point, I would like to see a .= operator, since this kind of "mutate and save" comes up surprisingly often

viewModel.EmailAddress = viewModel.EmailAddress.Trim()
David
  • 10,458
  • 1
  • 28
  • 40