Hi,
im making my new CakePHP project and I've got some problems with validating data, which comes from form. I mean i do know how to add custom rule but i don't know how should regex for 9 numeral telephone number looks like.

function checkPolishNumber($inputValue){

		$regex = 'what to put here?';
		
		if(!empty($inputValue['ask_telefon'])) {
			return preg_match($regex, $inputValue['ask_telefon']);
		}
		else {
			return true;
		}
			
	}

I think it should let through something like this:
+48 111 222 333
111 222 333
111-222-333
111222333

Is it possible to write regex like this?

P.S. Sorry for my creepy english.

Best regards,
Jola

Dani AI

Generated

Two practical options work well here: normalize-first (preferred) or a single anchored regex. gave the right idea about grouping and optional country code, but make sure your final pattern is anchored (use ^ and $) so partial matches don’t slip through, and remember that PHP’s preg_match returns 1/0/false — CakePHP validation expects a boolean, so cast or compare explicitly.

Normalize-first (robust, easy to maintain): strip every non-digit, remove an optional Polish country code, then check the remaining length equals 9.

function checkPolishPhone($data) {
    if (empty($data['ask_telefon'])) return true;
    $s = $data['ask_telefon'];
    $digits = preg_replace('/\D+/', '', $s);    // remove non-digits
    if (strpos($digits, '0048') === 0) $digits = substr($digits, 4);
    if (strpos($digits, '48') === 0)   $digits = substr($digits, 2);
    return strlen($digits) === 9;
}

If you prefer a single-pattern validator, use an anchored regex that only allows the Polish +48/0048 prefix and the three groups of three digits with optional separators; always trim the input and return a boolean (e.g. preg_match(...) === 1).

Practical notes: normalization is friendlier (accepts spaces, dashes, dots, parentheses) and gives a canonical value to save in the DB (store digits-only). For production-level international handling, consider a library (Google libphonenumber or a PHP port) — but for local Polish 9-digit validation the approaches above will reliably accept the examples you listed (e.g. +48 111 222 333, 111-222-333, 111222333).

Recommended Answers

All 2 Replies

First make sure what you want. For example, a regex for the last is:

/\d{9}/

So it could be extended to allow space/dashes in place 4 or 8:

/\d{3}[ -]?\d{3}[ -]?\d{3}/

Then, to match also a plus, two digits and a space/dash in front you need something like:

/(\+?\d{2}[ -]?)?\d{3}[ -]?\d{3}[ -]?\d{3}/
commented: nice +14

Thank you. I always find it difficult to write right regex. You explained it really nice. Thanks again. :)

Best regards,
Jola

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.