Form Validation (I want to restrict special characters in 1 of my form filed)

Re: Form Validation (I want to restrict special characters in 1 of my form filed)

by Angel - -
Number of replies: 3
The regex need delimiters, try with '/^[^_ ]+$/'

$mform->addRule('name', 'Field should contain only characters and numbers.', 'regex', '/^[^_ ]+$/', 'server');
Average of ratings: Useful (1)
In reply to Angel -

Re: Form Validation (I want to restrict special characters in 1 of my form filed)

by Aruna Kathiriya -

I added

$mform->addRule('name', 'Field should contain only characters and numbers.', 'regex',  '/^[^_ ]+$/', 'server');

But still it accepts the special chars.

Am I doing any mistake?



In reply to Aruna Kathiriya

Re: Form Validation (I want to restrict special characters in 1 of my form filed)

by Mark Johnson -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

As Darko said, "Add any other characters you do not wish to have in the text". The regex as written here will allow any character that's not an underscore. If you need to restrict other characters, you'll need to add them to the excluded class.

In general, if you are going to include regular expressions in your code, I would highly reccommend getting a good understanding of how they work and what they mean, not just copy/pasting blindly, as they are very powerful and easy to get wrong. Regexr is a helpful tool for explaining and testing expressions.

In reply to Mark Johnson

Re: Form Validation (I want to restrict special characters in 1 of my form filed)

by Aruna Kathiriya -
Yes Mark, you are right. But I have used

$mform->addRule('name', 'Field should contain only characters and numbers.', 'regex', '\'^£$%&*()}{@#~?><>,|=_+¬-]\', 'server');

But it didn't work either. I used http://buildregex.com/ to build my regex and used https://www.freeformatter.com/regex-tester.html to test. It workes fine on this site, but didn't gave any effect on Moodle.

Then I added "pattern" in HTML .
I changed
$mform->addElement('text', $field, get_string($field), 'maxlength="100" size="30" ');
to
$mform->addElement('text', $field, get_string($field), 'maxlength="100" size="30" pattern="[A-Za-z0-9]+"');

This solved my issue.
Thanks for your reply.