Laravel custom validation messages - laravel

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?

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.

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",
),

Related

How to get the error type of Validator on Laravel? [duplicate]

If there a way to check whether or not the validator failed specifically because of the unique rule?
$rules = array(
'email_address' => 'required|email|unique:users,email',
'postal_code' => 'required|alpha_num',
);
$messages = array(
'required' => 'The :attribute field is required',
'email' => 'The :attribute field is required',
'alpha_num' => 'The :attribute field must only be letters and numbers (no spaces)'
);
$validator = Validator::make(Input::all(), $rules, $messages);
if ($validator->fails()) {
In laymans terms, I basically want to know: "did the validation fail because the email_address was not unique?"
Check for a specific rule within the returned array of failed rules
if ($validator->fails()) {
$failedRules = $validator->failed();
if(isset($failedRules['email_address']['Unique'])) {
...
This will display an error and tell you what failed:
Controller
if($validation->fails()){
return Redirect::back()->withErrors($validation)->withInput();
}
foreach($errors->all() as $error) {
echo $error;
}
And in your blade template add this:
#foreach($errors->all() as $error)
<div>
{{$error}}
</div>
#endforeach
And that will return a message with whatever the error is. Email doesn't match. Field is required. Blah blah
You can also remove that email array from the $message. The validator will handle all that for you. You only want to use that if you want custom messages.
You can also try to var_dump this statement:
var_dump($validation->errors()); die;

Property "BankMaster.swift_code" is not defined

I am having issues rendering a modal when i click on add new button in yii with these error
CException
Property "BankMaster.swift_code" is not defined
This the view file (BankMaster/_form.php)
<?php echo $form->textFieldRow($model, 'swift_code', array('labelOptions' => array('class' => 'col-md-8 bank-master-settings-cls'), 'class' => 'col-xs-12 col-sm-12 col-md-12 col-lg-12', 'maxlength' => 100)); ?>
swift_code is the changes i made.
This the Model file (BankMaster.php)
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('full_name, short_name,iban_no,branch,payroll_status', 'required'),
array('full_name, address, email,swift_code', 'safe'),
array('opening_balance', 'numerical'),
array('ledger_code', 'uniqueCode'),
array('telephone,account_no, company_id', 'numerical', 'integerOnly' => true),
array('short_name,ledger_code', 'length', 'max' => 100),
array('full_name, email', 'length', 'max' => 100),
array('email', 'email'),
array('short_name', 'uniqueInLedger'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, short_name,account_no,iban_no,opening_balance,op_balance_dc,branch_type,branch, full_name, address, telephone, email, payroll_status, is_default', 'safe', 'on' => 'search'),
);
}
swift_code is the changes i made too.
Then i added a column in erp_bank_master table
SOLUTION: "wp_105578" was the right database instead of "wpexp_dev"

How to validate HTML response in post array in codeigniter

I am using tinymce for to add user cover letter related to the application.
This what my post array look like:
Array
(
[cover_letter] => <p>Test Cover Letter</p>
<ol>
<li>Need to save this data</li>
</ol>
<p><strong>Thanks</strong></p>
)
Simply I have used the require validation rule for this.
'candidate_cover_letter' => array(
array(
'field' => 'cover_letter',
'label' => 'Cover Letter',
'rules' => 'required'
)
)
I get the validation error regarding this like Cover Letter require.
I have two main problem:
How to validate HTML post array data
Is this best practice to save data like this? if no then how should i save this data?
First of all, in Codeigniter if we want to do form validations we need to go like this :
$config = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required',
'errors' => array(
'required' => 'You must provide a %s.',
),
)
);
$this->form_validation->set_rules($config);
You can refer here
so, your code here should be like this in the controller:
$config =array(
array(
'field' => 'cover_letter',
'label' => 'Cover Letter',
'rules' => 'required'
)
);
$this->form_validation->set_rules($config);
You can add extra fields in the $config like the example above.
Another thing that you asked, "How you should save the data ?"
I would suggest you to use a field in the database table with type "TEXT" and it should be okay for you.
After you hit submit you get redirected back to your controller somewhere. One way to utilize CI form validation is:
//look to see if you have post data
if($this->input->post('submit')){
//points to applications/config/form_validation.php (look at next chucnk to set form_validation.php)
if($this->_validate('cover_letter')){
//rest of your post logic
//get data to upload to database
$data = [
'cover_letter'=>$this->input->post('cover_letter'),
'user_id'=>$this->input->post('user_id')
];
//save data to database ..also this should be moved to a model
$this->db->insert('name of table to insert into', $data);
}
//if you post doesnt not get validated you will fall here and if you have this chucnk of code in the same place were you have the logic to set up the cover letter you will see a pink message that says what ever error message you set up
}
Set up form validation.php
<?php
$config = [
//set up cover letter validation
//$this->_validate('cover_letter') maps to here and checks this array
'cover_letter' => [
[
'field'=>'cover_letter',
'label'=>'Cover Letter Required',//error message to return back to user
'rules'=>'required'//field is required
],
//example to add additional fields to check
[
'field'=>'observations',
'label'=>'Observations',
'rules'=>'required'
],
],
]

Validation in laravel 4

Iam new in laravel.
Iam trying to laravel form validation.
my validation code is
$rules = array(
'studname'=>'required',
'pmobile'=>'required|digits:10',
'studadno'=>'required|unique:wys_students,studadno',
'studrollno'=>'required|numeric|unique:wys_students,studrollno',
'studgender'=>'required|in:male,female',
'studdob' =>'required',
'studbldgrp'=>'required|in:O+ve,O-ve,A+ve,A-ve,B+ve,B-ve,AB+ve,AB-ve,Other',
); $messages = array(
'required' => 'The :attribute field is required.',
'in' => 'The :attribute must be one of the following types: :values',
);
$validate=Validator::make(Input::all(), $rules, $messages); `
output is-:
Student Name :The studname field is required.
Parent Mobile:
The pmobile field is required.
but, I want eg: student name field is required..
how to change my validation code?
$messages = [
'studname' => 'student name field is required.',
];
$validator = Validator::make($input, $rules, $messages);
You can pass the $messages array as the third parameter and you can define custom messages in the $messages array
There are 2 options.
Firstly you can change the form field name to student_name and then you will see message "The student name field is required"
Secondly you can write custom messages for each of the fields. In you case it will be:
$messages = array(
'studname.required' => 'The Student Name field is required.'
);
$rules = array(
'studname' => 'required',
'pmobile'=>'required|digits:10',
'studadno'=>'required|unique:wys_students,studadno',
'studrollno'=>'required|numeric|unique:wys_students,studrollno',
'studgender'=>'required|in:male,female',
'studdob' =>'required',
'studbldgrp'=>'required|in:O+ve,O-ve,A+ve,A-ve,B+ve,B-ve,AB+ve,AB-ve,Other',
);
$messages = array(
'studname.required' =>'The Student Name field is required.',
'pmobile.required'=>'The Parent Moblie field is required.',
'studadno.required'=>'The Student Admission Nubmer field is required.',
'studrollno.required'=>'The Student RollNubmer field is required.',
'studgender.required'=>'Must be one of the following types: :values',
'studdob.required'=>'The Student Date of Birth field is required.',
'studbldgrp.in'=>'Must be one of the following types: :values',
);
$validate=Validator::make(Input::all(), $rules, $messages);
You can provide translations of the attribute names in app/lang/xx/validation.php.
There's an attributes array at the very bottom, just add your attributes:
'attributes' => array(
'studname' => 'student name',
'pmobile' => 'parent mobile',
// and so on
),
This way you don't have to rewrite the message for every field and every rule. And you can even use those field names across multiple forms.

CakePHP when using $model->save() validate rules and skip other rules

I'm using CakePHP 2.0 and I have a model that I use validation on it like this:
var $validate = array(
'title' => array(
'unique_rule'=>array(
'rule' => 'isUnique',
'on' => 'create',
'message' => 'This title has already been taken.'
),
'required_rule'=>array(
'required' => true,
'allowEmpty' => false,
'message' => 'The title field is required.'
)
)
);
, and in the controller I have an edit action and I use $model->save() to save date from $this->request->data, but it fails the isUnique validation rule, although it is not a new record insertion.
Is there any way to specify that it is an existing record, not a new one ?
If I got the question right you have to set the model's ID before calling $model->save(); so cakephp knows it's an update.
See http://book.cakephp.org/2.0/en/models/saving-your-data.html:
"Creating or updating is controlled by the model’s id field. If $Model->id is set, the record with this primary key is updated. Otherwise a new record is created:"
<?php
// Create: id isn't set or is null
$this->Recipe->create();
$this->Recipe->save($this->request->data);
// Update: id is set to a numerical value
$this->Recipe->id = 2;
$this->Recipe->save($this->request->data);
your validation array is wrong you haven't set a rule for 'required_rule' wich might trigger the isUnique error message.
var $validate = array(
'title' => array(
'unique_rule'=>array(
'rule' => 'isUnique',
'on' => 'create',
'message' => 'This title has already been taken.',
'last' => true
),
'required_rule'=>array(
'rule' => array('notEmpty'),
'message' => 'The title field is required.'
)
)
);
Also remember that using required=>true will NOT result check for actual data, it only wants the field to be present in the data-array and "" is also considered as present

Resources