How To validate form in moodle to accept only phone number start with 966 or 05

How To validate form in moodle to accept only phone number start with 966 or 05

by sarah aldossari -
Number of replies: 2

I want to validate a textbox to accept only phone number that starts with either 05 or 966. Any ideas how can I do that? My condition does NOT work it will not Validate the entered data.

This is my textbox

$mform->addElement('text', 'phone', get_string('StudentUpdatePhoneNumber'), $attributes);

function validation($data, $files) {
        global $CFG, $DB;

        $errors = parent::validation($data, $files);


        if (empty($data['phone'])) {
            $errors['phone']= get_string('ErrorEmptyPhoneNumber');
        }
        else if ( !is_numeric ($data['phone'])) {
            $errors['phone']= get_string('ErrorNotNumPhoneNumber');
        }

        else if(preg_match("^[966](.*)$", $data['phone'])) {
            $errors['phone']= get_string('ErrorStartWithPhoneNumber');

        }

        return $errors;
      }

Average of ratings: -
In reply to sarah aldossari

Re: How To validate form in moodle to accept only phone number start with 966 or 05

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

There are a few problems with your preg_match line:

  • Your pattern is not delimited, you need to surround to start and end with a delimeter such as / or ~, e.g. "/^[966](.*)$/".
  • Square brackets define a class of character you are looking for, so ^[966](.*)$ looks for a string starting with a 9, or a 6, or a 6, followed by any number of other characters.
  • You aren't looking for 05 at all. One possible pattern for your rule would be /^(966|05)/

Since what you are looking for is quite simple, it might be more efficient to use a PHP string comparison function to check what's at the start, like strpos('966', $data['phone']) !== 0 && strpos('05', $data['phone']) !== 0

Average of ratings: Useful (1)
In reply to Mark Johnson

Re: How To validate form in moodle to accept only phone number start with 966 or 05

by sarah aldossari -

Thank you so much, that really helped.