1

I have a Post model which has the following validation rules:

public $validate = array(
    'title' => array(
        'between' => array(
            'rule' => array('between', 1, 60),
            'message' => 'Between 1 and 60 characters in length'
        ),
        'format' => array(
            'rule' => array('custom', '~[a-zA-Z0-9\s-]~'),
            'message' => 'Alphanumeric characters, spaces and dashes (-) only'
        )
    ),
    'body' => array(
        'between' => array(
            'rule' => array('between', 1, 65535),
            'message' => 'Between 1 and 65535 characters in length'
        )
    ),
    'slug' => array(
        'between' => array(
            'rule' => array('between', 1, 60),
            'message' => 'Between 1 and 60 characters in length'
        ),
        'format' => array(
            'rule' => array('custom', '~[a-zA-Z0-9-]~'),
            'message' => 'Alphanumeric characters and dashes (-) only'
        )
    )
);

I also have a view to insert a new post which looks like this:

<?php $this->Html->script('add-post', array('inline' => false)); ?>

<h1>Add post</h1>

<?php echo $this->Form->create('Post'); ?>
<?php echo $this->Form->input('title'); ?>
<?php echo $this->Form->input('body'); ?>
<?php echo $this->Form->input('slug'); ?>
<?php echo $this->Form->end('Publish'); ?>

Now, when I submit the form with the title being something like blog post title £$&£$^£$ it goes through and gets inserted, despite the regex not matching the symbols in that title. This happens on all fields where regex is used to check the format.

However, if I try to submit a post which doesn't pass the between rule (like a title over 60 characters) it successfully throws up a validation error.

What could be going wrong here?

1 Answer 1

2

Your regex pattern is only checking that at least one of those characters is found anywhere in the string. So if you were to post just £$&£$^£$ by itself it would fail because the valid characters aren't found anywhere in that string. You should replace the rule with this:

~^[a-zA-Z0-9\s-]+$~
Sign up to request clarification or add additional context in comments.

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.