1

I'm using in Php Sanitize and Validate Filters but I have problems to add some rules, I have some basic knowledge of php so I think this question is easy for you.

if ($_POST['ccp_n'] != "") {
            $ccp = filter_var($_POST['ccp_n'], FILTER_SANITIZE_NUMBER_INT);
            if (!filter_var($ccp, FILTER_VALIDATE_INT)) {
                $errors .= 'Insert a valid code.<br/>';
            }
        } else {
            $errors .= 'Insert a code.<br/>';
        }

I need to add a minimum and maximum number of characters (14-15) and I want to accept this characters ( - or space ) .The exact sequence is 0000-0000-0000 (the last four digits could be 5 too

Thanks

2
  • 2
    "Something like" is a bit vague. Define the variable length and the positions of the hyphen in the string a bit more. Besides the hyphen should only digits be allowed? Commented Sep 13, 2011 at 11:31
  • Yes, only digits. The exact sequence is 0000-0000-0000 (the last four digits could be 5 too. Commented Sep 13, 2011 at 11:40

2 Answers 2

2

You can use preg_match and apply a regular expression.

preg_match ( string $pattern , string $TestString) See here in detail

The pattern is the problem. You need to define in detail what is allowed.

For example, the pattern:

'~^\d{4}-\d{4}-\d{4,5}$~D'

would be the whole string from start ^ to the end $. 4 digits, hyphen, 4 digits, hyphen, 4 to 5 digits.

See it here on Regexr

Update:

I added the D modifier to the end, otherwise the $ not only match to the end of the string, but also before a newline as last character in the string. See here for php modifiers in detail

Sign up to request clarification or add additional context in comments.

3 Comments

Don't forget the /D modifier.
@Geert, thank you for teaching something new. updated my answer.
In this case, applying to my example, I will use FILTER_VALIDATE_REGEXP with this regular expression. Thanks for the help.
0

Use a regular expression with preg_match(). Alternatively, you can also use sscanf() to parse the input from a string according to a format.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.