1

I'm trying to validate a UK postcode using Laravel. Here's what I've got:

//routes.php
    $rules =  array(
        'pcode' => array('required:|Regex:/^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][‌​0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$/') 
    );

    $messages = array(
        'required' => 'The :attribute field is required.',
        'pcode' => array('regex', 'Poscode should be a valid UK based entry'),
    );

    $validator = Validator::make(Input::all(), $rules, $messages);

In my blade:

<input id="postcode" name="pcode" value="{{Input::old('pcode')}}" type="text" placeholder="Postcode" class="form-control" xequired="" />
    @if( $errors->has('pcode') ) <span class="error" style='background-color: pink;'>{{ $errors->first('pcode') }}</span> @endif

If I submit the form with an empty pcode field, it warns me for a required field. If I enter an invalid postcode, '74rht' say, my validator does nothing or fails to display my custom message as defined above?

Patrick Reck
  • 11,246
  • 11
  • 53
  • 86
cookie
  • 2,546
  • 7
  • 29
  • 55

2 Answers2

4

The Laravel manual states:

Note: When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

Change the $rules to this structure:

$rules = array(
    'pcode' => array(
        'required',
        'Regex:/^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][‌​0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$/'
    ) 
);

If that doesn't work, then maybe your regex isn't valid, try to use a easier regex to check if the validator works.

Sven van Zoelen
  • 6,989
  • 5
  • 37
  • 48
1

Fist, you will want to register a custom validation rule with the validator.

    Validator::extend('pcode_rule_name', function($attribute, $value)
    {
        return preg_match('/^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][‌​0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$/', $value);
    });

src: http://laravel.com/docs/validation#custom-validation-rules

Then you will want to specify custom messages in app/lang/en/validation.php

You will find a place to add your custom message for your your rule

     'custom' => array(
        'attribute-name' => array(
            'rule-name' => 'custom-message',
        ),
     ),

You can add a rule like so:

     'custom' => array(
        'pcode' => array(
            'pcode_rule_name' => 'Post Code should be a valid UK based entry',
        ),
     ),

There will also be an array to name your "pcode" field so it will be more eloquently named for rules like "required".

    'attributes' => array(),

just add the name like so

    'attributes' => array(
         'pcode' => 'Postal Code",
    ),
Brett T
  • 81
  • 1
  • 6