Laravel validator for CSS selectors

Last week I was building a backend tool in Laravel, where you could create layout in bootstrap 3 and add CSS selectors like id or class to any container. You wanted to be able to enter more than one class name into input field. Let's say that you want to add 2 classes: col-xs-6 infoBox_4. Laravel hasn't validator for this type of string so I decided to make one. I needed to have validator which accepts alphabetic characters, numbers, underscore symbols, hyphens and spaces. I didn't want to make it over complex, but still wanted to validate that users enters valid css selectors.

Creating rule

We need to create and register the new validation rule with the Validator facade. I went to regulex, my favourite regular expressions visualiser and created the regular expression pattern.

Regular expression for alphabetic characters, numbers, underscore, hyphens and space

Extending validator

Now that we have pattern, we will extend validator. We want to have this rule available everywhere throughout the project, so we will put it to some global space app/start/global.php.


    // app/start/global.php 

    ...
    
    Validator::extend('css_selectors', function ($attribute, $value) {
        return preg_match('/^[A-Za-z0-9-_\s]+$/', $value);
    });

The custom validator closure receives in this case two arguments: the name of attribute being validated and the value of the attribute. If you don't like closures, you may pass a class and method Validator::extend('css_selectors', 'ValidatorController@validateCssSelectors');.

The validator extension is very simple, if the return value is true, then the rule is ok. If the return value is false, then the rule failed. We also want to show some error message. Lets add it somewhere to lang file for validator.


    // app/lang/en/validation.php

    return array(
    ...
    "css_selectors"   => "The :attribute may only contain letters, numbers, spaces, underscores and hyphens ",
    ...
    );
    

The new rule is now registered globally and ready to use.

If you decide to create more validation rules later, it is better to separate them from app/start/global.php file into other one. I would suggest to create app/validators.php and put all validator extensions in this new file. Then we will add only one line into global.php require app_path().'/validators.php';

Using the new rule



        $rules = array(
            ...,
            'idName'        => 'required|css_selectors',
            'className'     => 'required|css_selectors'
        );
    

Conclusion

We learned how to create simple regexp pattern and how to extend Validator with a new Laravel validation rule. I also showed you how to call class with method instead of closure for more complex validators. If you have defined many own validators, then separate them into new file to preserve SRP. The above paths are made in Laravel 4.2, but as I know, no changes were made to Validator in Laravel 5.1 and the only changes are in slightly different locations of files.

Tags: laravel, php, css, validator


Move Local Git Repository to Bitbucket

As I described in previous post, when I joined to my current company, we hadn't any versioning system, not even SVN and we used to FTP all files to XY number of backup folders. I introduced Git on local servers. Everything started to seem better, but after some time we started to work with some people from abroad and one of colleagues started to work from home. That meant that they couldn't connect to local network to push to GIT. Setting up VPS wasn't option, as our boss was worried lot about the security and didn't want to people connect to office network from home, etc. Private repositories on github are paid for and codebases of our clients couldn't be shared world wide. I remembered, that in one of my previous jobs we used bitbucket, which was free to team of 5 developers and offer unlimited number of repositories. It seemed that boss will happily pay nothing for free tool and manager will accept that repositories are private with access management.

What we want to achieve?

We already had our codebase under git repository. I didn't want to loose the history of commits. We also had some branches, with some dev work on it. Those branches wasn't aprroved and safe to merge into master branch. I wanted to have all this stuff also on bitbucket. You will see that this process is really easy. Our current repository is tracking the existing remote repository on our local server. So first, we will remove the tracking of remote repository on local working directory, then we will create new repository in bitbucket and finally we will attach our repository to bitbucket remote and push all changes to repository.

What we need?

  • bitbucket account (free)
  • unix terminal
  • local working directory of GIT repository.

1. Detach the remote from your local repo

First let's go to the projects folder


    Stefans-iMac:~ stefan$ cd Projects/myproject.dev/
    Stefans-iMac:myproject.dev stefan$ 

Git has command to manage set of tracked ("remotes") repositories. It's called git-remote.


    Stefans-iMac:myproject.dev stefan$ git remote
    origin

As you can see our working directory is tracking origin repository. Using the verbose parameter -v we can even check it's remote url after name


    Stefans-iMac:myproject.dev stefan$ git remote -v
    origin  user@192.168.1.26:Repositories/myproject.git (fetch)
    origin  user@192.168.1.26:Repositories/myproject.git (push)

Working directory can track even more than one remote and you can usually pull or push to any of them, but that depends on permissions. Now we are going to remove the only remote, the origin.


    Stefans-iMac:myproject.dev stefan$ git remote rm origin

2 .Create new Bitbucket repository

We need to login to our bitbucket account and select to create new repository form the top menu, then fill the simple form and voila. We have new repository.

Creating new Bitbucket Repository

In next step we will need to have the link to repository and for that we will need https url. You can find it in repository Overview page and make a copy into your clipboard.

Bitbucket Repository url

Mine GIT https URL looks like this: https://skecskes@bitbucket.org/skecskes/myproject.git

3. Attach your code to new remote repo and push your project

Now lets get back into terminal into our project folder. We will use the URL of our remote repo to attach it to our project.


    Stefans-iMac:myproject.dev stefan$ git remote add origin https://skecskes@bitbucket.org/skecskes/myproject.git

We can check now if the remote repo is correctly attached.


    Stefans-iMac:myproject.dev stefan$ git remote -v
    origin  https://skecskes@bitbucket.org/skecskes/myproject.git (fetch)
    origin  https://skecskes@bitbucket.org/skecskes/myproject.git (push)

Yes, we can see it is attached. So we can push our project to remote repository. Probably you will need to enter your password for bitbucket. You may also wait a few moments while project is uploaded.


    Stefans-iMac:myproject.dev stefan$ git push -u origin --all
    Password for 'https://skecskes@bitbucket.org': 
    Counting objects: 18702, done.
    Delta compression using up to 4 threads.
    Compressing objects: 100% (18666/18666), done.
    Writing objects: 100% (18702/18702), 73.54 MiB | 636.00 KiB/s, done.
    Total 18702 (delta 16400), reused 0 (delta 0)
    To https://skecskes@bitbucket.org/skecskes/myproject.git
     * [new branch]      booking-system -> booking-system
     * [new branch]      develop -> develop
     * [new branch]      master -> master
    Branch booking-system set up to track remote branch booking-system from origin.
    Branch develop set up to track remote branch develop from origin.
    Branch master set up to track remote branch master from origin.

The project code is now successfully pushed to remote repository. It also created all branches I had locally in remote repository. We can now log into bitbucket and see all our code there, altogether with commits history. There is one more step you might like to do, just in case you have used tagging (v.1.0.0 etc.). The tags are being added to repository separately, by using command git push -u origin --tags , which pushes all tags from your local repository to the new bitbucket repository.

History of repository commits

Conclusion

I showed you how easy is to create new repository in bitbucket. We have learned how to chcek what remote repos is tracking your project, we detached remote bare GIT repository from the working directory of project and we learned how to attach another remote repo to local project. In steps above I used the bitbucket, but the process would be very same for any other remote repo (github, your subdomain, etc...). I also hope that there are no other obstacles preventing my dev team members from using git and revert to ftp backups.

Tags: git, bitbucket