Hi Everyone, I am trying to allow only numbers and dashes into one of my text inputs on a form.
For example: 1-1, 1-0, 2-3 etc

And I have the following to validate numbers only

    function validate_cscore($variable) {
        return is_numeric($variable);

the above works great with the following error checking

        $hint = 'Invalid Mobile Number';
        registerError( $hint, $hint, $error_title, '<p><font color="#ffffff"><strong>Invalid correct score detected</strong></font></p>' );

I started doing some digging around and found the following to allow me to add the ability to use dashes

    $csValid = array('-');

With the following error message

    if(!ctype_alnum(str_replace($csValid, '', $cscore))) { 
        $hint = 'Name';
        registerError( $hint, $hint, $error_title, '<p><font color="#ffffff"><strong>Correct score format is 1-1, 2-0, 2-1 format</strong></font></p>' );

The above allows 1-a, b-2, 3-c etc
But get the error message "invalid correct score" error message as there is a dash in my in my input as 1-1, 2-0, 2-1 etc
How can I ensure a user enters the correct score format, but also check for instances of 1 a, 2-a, a-1 etc

Thanks in advance everyone.

2 Years
Discussion Span
Last Post by lloyd.farrell.7

Try with preg_match():

function validateScore($score)
    $score = trim($score);
    $pattern = '/^\d{1,2}[\s]?-[\s]?\d{1,2}$/';
    return preg_match($pattern, $score) == 1 ? true : false;

Valid inputs are:

var_dump(validateScore('2- 0'));
var_dump(validateScore('2 -0'));
var_dump(validateScore('2 - 0'));

Spaces around the string are removed by trim(). To validate only those without spaces between the dash change the pattern to:

$pattern = '/^\d{1,2}-\d{1,2}$/';

preg_match() returns integers 1 for true, 0 for false, the above function, instead, will return booleans. The flag \d will search for digits, {1,2} limits the range to 0-99.

Edited by cereal


Hi Cereal, Thanks for this, Just getting round to trying what you have suggested, Once I get this working I will let you know,
Thanks again,

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.