Login / registration username regexp validation

Hello there.

I’m using the Login extra and the snippet [[!Register]] to register an user.
I don’t want crazy user names that can broke something in there so I’m trying to validate the username to only accept: lowercase, uppercase, numbers that is it. [a-zA-Z0-9]+$

No extra characters of any kind and no spaces :strip=^ ^

But [a-zA-Z0-9]+$ still accepting characters between letters.

Any guide please?

here the validation part:

&validate=`nospam:blank,
username:required:minLength=^4^:maxLength=^15^:strip=^ ^:regexp=^/[a-zA-Z0-9]+$/^,
'

Thanks!!!

So if this is a regex pattern, the $ symbol is anchoring the pattern to the end of the string, so I’d imagine that your pattern would accept anything that ends in one or more alphanumeric characters. Without knowing too much of the specific nuances of what you’re doing (I’m replying from a phone right now), I would suggest trying something like ^[a-zA-Z0-9]+$ where the ^ symbol matches the beginning of a string. That might help some maybe…

Are you able to use single quotes instead of carets for the second level of delimiters here?

Thanks for your answer mate.

I tried using the ^ but it’s not working, looks like the syntax is not accepted.

regexp=^/[a-zA-Z0-9]+$/^

I’m not sure if that is a FormIt/Register snippets problem, in that case what might be the alternative?

You need to add a ^ after your first /

Try something like regexp=^/^[a-zA-Z0-9]+$/^

The extra ^ makes it look at the entire string. Without it the expression is just matching on the last character meaning john!doe would pass but johndoe! would not.

And if it is a bug with Login/Register then create a custom validator instead of trying to inline the regex. A custom snippet that’s as basic as this:

$output = preg_match('/^[a-zA-Z0-9]+$/', $input);
return $output;

Would validate it for you. If I remember correctly Login uses the same validation stuff as FormIt so you should be able to create a custom validator for it (I think) https://docs.modx.com/current/en/extras/formit/formit.validators

1 Like

My guess is that Login would choke on using the ^ character as part of the pattern since it’s using them like quotes around the property value. Nick’s suggestion of a custom validator may be your best bet.

1 Like

Nick thanks mate.
just a couple changes to make it work, but it’s a great solution:

<?php
$output = preg_match('/^[a-zA-Z0-9]+$/', $value);
if(!$output) {
    $validator->addError($key, 'Error text here');
}

Just use $value instead of $input
and It’s necessary to include $validator->addError to display the field error when it returns false.

In addition I include a lexicon error form:

<?php
$output = preg_match('/^[a-zA-Z0-9]+$/', $value);
$subject = $modx->lexicon('username.error');
if(!$output) {
    $validator->addError($key, $subject);
}

Thanks @nick2687 and @bobray !