user2133177
user2133177

Reputation: 1

data validation do not allow numeric only

I am new to cakephp and I am trying to make a data validation for a program name. I want my program name to allow only alphaNumeric or characters. I don't want it to allow numeric only or special characters. Actually is not allowing Numeric or alphaNumeric, because of the second rule. Here is my code

$validate = array(    
    'program_name' => array(
        'required' => array(
            'rule' => 'isUnique',
            'allowEmpty'=> false,
            'message' => 'This Program Name already exists. Please enter a Program Name'
        ),
        'alphaNumeric'=> array(
            'rule' => 'alphaNumeric',
            'message'=> 'Please enter a valid name'
        ),
        'name' => array(
            'rule'    => '/^[a-zA-Z]*$/',
            'message' => 'Only letters or alphaNumerics. Please enter a valid name')
        )
    )
    //Validation rules for other fields, if any
);

Upvotes: 0

Views: 2116

Answers (1)

Joep
Joep

Reputation: 651

Your use of 'required' is off, it probably should be this:

$validate = array(    
    'program_name' => array(
        'isUnique' => array(
            'rule' => 'isUnique',
            'allowEmpty'=> false,
            'required' => true,
            'message' => 'This Program Name already exists. Please enter a Program Name'
        ),
        'alphaNumeric'=> array(
            'rule' => 'alphaNumeric',
            'message'=> 'Please enter a valid name'
        ),
        'name' => array(
            'rule'    => '/^[a-zA-Z]*$/',
            'message' => 'Only letters or alphaNumerics. Please enter a valid name')
        )
    )
    //Validation rules for other fields, if any
);

Now, having fixed the use of 'required' we'll move on to your question. If you want to check whether there the string consists of alphaNumeric characters, but not only numbers: you need to edit the regex defined in your 'name' rule. I'd suggest using the regex from the answer to this question. So: replace /^[a-zA-Z]*$/ with the regex from the post I mentioned, and then remove the rule called alphaNumeric, so you code looks like this:

$validate = array(    
    'program_name' => array(
        'isUnique' => array(
            'rule' => 'isUnique',
            'allowEmpty'=> false,
            'required' => true,
            'message' => 'This Program Name already exists. Please enter a Program Name'
        ),
        'name' => array(
            'rule'    => '/^(?![0-9]*$)[a-zA-Z0-9]+$/',
            'message' => 'Only letters or alphaNumerics. Please enter a valid name')
        )
    )
    //Validation rules for other fields, if any
);

Upvotes: 1

Related Questions