Sign Up (Cloud functions field validation)

Hey guys,
So I’m trying to make some special validations on sign up with Cloud Functions but my code doesn’t seem to work and I’m not sure why because I followed the docs.

const validateSignUp = (request) => {
  // Validate username
  if (!(/^[a-zA-Z0-9.\-_]*$/.test(request.username))) {
    throw "Invalid Username";
  } else if (request.username.length < 2) {
    throw "Invalid Username";
  } else if (request.username.length > 32) {
    throw "Invalid Username";
  }

  // Validate password
  if (request.password.length < 4) {
    throw "Invalid Password.";
  }
}

Moralis.Cloud.beforeSave(Moralis.User, () => {
  // any additional beforeSave logic here
}, validateSignUp);
1 Like

This is how I was able to call a validation function:

const validateSignUp = (request) => {

  logger.info("before printing username in validateSignUp");
  logger.info(request.object.get("username"));
  logger.info("after printing username in validateSignUp");
  

  if (!(/^[a-zA-Z0-9.\-_]*$/.test(request.username))) {
    throw "Invalid Username";
  } else if (request.username.length < 2) {
    throw "Invalid Username";
  } else if (request.username.length > 32) {
    throw "Invalid Username";
  }

  // Validate password
  if (request.password.length < 4) {
    throw "Invalid Password.";
  }
}

Moralis.Cloud.beforeSave(Moralis.User, (request) => {
  logger.info("in before Save");
  logger.info("before printing request in beforeSave");
  logger.info(JSON.stringify(request));
  logger.info("after printing request in beforeSave");

  logger.info("before printing username in beforeSave");
  logger.info(request.object.get("username"));
  logger.info("after printing username in beforeSave");
  validateSignUp(request);
});
1 Like

Thanks that works, but I guess the docs are wrong then?

Also where can I check those logs printed by logger.info?

You can check the logs in server dashboard in logs -> info

1 Like

I wasn’t able to run that syntax either. :thinking: Will have to enquire regarding this.

1 Like

When i use this code i get “TypeError: Cannot read properties of undefined (reading ‘length’)” when i use .lenght in condition.

that usually means that the variable before .length is undefined

you could update the code to check if the user has a password

Seems like i have it all … can’t figure it out