My form has a cellphone and a phone field. I want the user to fill either one of the fields, or both, but not neither.
I've seen ways to do it in other languages, but could I have some advice on how to do it with Codeigniter?
You can do it as:
$this->form_validation->set_rules('phone', 'Your validation message.', 'callback__phone_check');
And make a function:
function _phone_check() {
//check for phone and cellphone field.
//make sure one field is not empty and return accordingly
}
Hope that helps
Just wanted to throw some quick code snippets your way. I wanted to accomplish this and this question was one of the first entries in google when I did my search. I took inspiration from the other answers and here's what I did which worked for me (YMMV):
$this->form_validation->set_message('contactVerify', 'Either Phone or Email is required');
...
$this->form_validation->set_rules('phone', 'Phone', 'trim|callback_contactVerify[email]|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|callback_contactVerify[phone]|valid_email|xss_clean');
...
public function contactVerify($contact, $otherField) {
return ($contact != '' || $this->input->post($otherField) != '');
}
Since this is a very simple validation function, I pre-set the error message so I don't have to set it inside validation function. I pass in the other field I want to check as the second argument via the square brackets.
Hope this is useful.
Just do a JS validation on client-side, and PHP validation on server-side (or use CI's form helper)... Anyway, PHP should look something like this:
if ($_POST['cellphone'] == '' OR $_POST['phone' == '') {
// do stuff like make an notification, alert, etc... and take users back to the form
}
Related
PHP Controller:
$this->form_validation->set_rules('phone', $this->language->get_text('phone', 'global'), 'max_length[0]');
I need to put an IF condition for the above line code to return this:
if (The_Above_Line_Code is NOT empty)
{
$this->output->set_status_header(400);
exit;
}
So, if the input field don't contain characters it's OK and the contact form to work properly, but if contain characters, then should return a blank page (set_status_header(400)).
PS: It's a way to combat spam in contact form.
$this->form_validation->set_rules('phone', $this->language->get_text('phone', 'global'), 'max_length[0]|numeric');
If it's not a number then form validation fails. I don't see the logic in serving a 400.
https://www.codeigniter.com/userguide3/libraries/form_validation.html?highlight=form%20validate#rule-reference
Update
After understanding your reasoning better you can simply do this:
if (!empty($this->input->post('phone'))) {
show_404(); // sets header + exits
}
You can even use show_404() (CI function) as a way to log the error: show_404('bot detected', true);.
I'm running CI form validation and using form_error() to display errors individually for each field. The problem, though, is that the form_error() function only returns the first validation error
Example field:
<input type="text" name="value" value="short">
validation script:
$validationRules = "min_length[6]|numeric";
$this->form_validation->set_rules(
'value',
'lang:mod_the_field',
$validationRules
);
if($this->form_validation->run() === FALSE){
echo form_error('value');
}
The above outputs: <p>The Value field must be at least 5 characters in length.<\/p>
Although the field also fails validation as a numeric value.
I cannot seem to find documentation on this. Is there a simple step I am missing to get all validation errors for a single field output? Is there a better solution than running the validation multiple times, once for each rule?
EDIT:
To be clear, the output I'm looking for in this particular example is:
<p>The Value field must contain only numbers.</p>
<p>The Value field must be at least 5 characters in length.</p>
One solution is to run the validation once for each rule and aggregate the output, but I'm trying to find out if there is a way to do this out of the box in CI?
SOLUTION:
I checked the Form_validation library and found that Samutz' comment is correct. The script breaks out and returns after the first validation error.
rather than extending any classes, I changed my code to iterate over each rule and concatenate the error string like so:
$validationRules = "min_length[6]|numeric";
$validationRules = explode('|', $validationRules);
$errors = '';
foreach($validationRules as $rule){
$this->form_validation->set_rules(
'value',
'lang:mod_the_field',
$rule
);
if($this->form_validation->run() === FALSE){
$errors .= form_error('value');
}
}
$errors = ($errors) ? $errors : FALSE;
echo $errors;
The problem
When testing for errors in a CI form that errors served by validation_errors() in form helper are not exactly what I would call 'accessible'.
Sure they are neat in the way that there's an error message presented for every error (so failing to populate both user name and password when they are required, will display two error messages by default), but this should be taken a step further. I'm talking about error labels, e.g.:
<label for="password">The Password field must be at least 6 characters in length</label>
So users can click on error and get straight to field that needs fixing.
The idea
My first idea was to write a wrapper for form helper or somehow extend the form class. While this seemed as a good solution, a deeper study of validation class usage revealed a quicker fix. By default, rule for password could look like this:
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[6]|md5');
Where set_rules() method parameters are as follows:
Password field name attribute (the same which you've defined)
Quoting the manual - A "human" name for this field, which will be inserted into the error message.
Validation rules for password field (in the above example password is required and at least 6 characters long) plus some modifiers (trimming spaces and instant conversion to md5).
A simple solution is to insert a label into second parameter, which will be literally used for displaying the error. It could look like this:
$this->form_validation->set_rules('password', '<label for="password">Password</label>', 'trim|required|min_length[6]|md5');
But why not take it a step further and use form_label() from form helper? That would result in:
$this->form_validation->set_rules('password', form_label('Password', 'password'), 'trim|required|min_length[6]|md5');
As you've probably noticed, the fix will result in a slightly different code that we were aiming at:
The <label for="password">Password</label> field must be at least 6 characters in length
Only the actual field name is wrapped in label tag. But hey - with some simple styles (below) it's not that bad at all. For more organised styles it would be nice to add a custom class to that label, or better yet - wrap the whole error message in some unique container (so you'll be able to specify styles only for that error label) using set_error_delimiters():
$this->form_validation->set_error_delimiters('<div class="form_error">','</div>');
That will result in following html:
<div class="form_error">The <label for="password">Password</label> field must be at least 6 characters in length</div>
Add some styles to that:
.form_error label {color:#F00;text-decoration:underline}
Hope you can do more with form_error() at this point:
// in stylesheet
.form_error label {color:#F00;text-decoration:underline}
// in form controller
$this->form_validation->set_error_delimiters('<div class="form_error">','</div>');
$this->form_validation->set_rules('password', form_label('Password', 'password'), 'trim|required|min_length[6]|md5');
just stumbled upon this myself and found a way around it. It's not really an orthodox solution but here it is
$errors = validation_errors('/', '/');
$errors = explode("/", $errors);
echo $errors[1];
This will only output the first error in the array.
EDIT: Make sure you check if your array has more than 1 value in it
if(count($errors) > 1) {
echo $errors[1];
}
first error
second error
box p:nth-child(2){display: none;}
I need to check if the email the user enters during registration is valid/real, meaning they can't just enter whatever they want as long as it meets the proper email format, I need to actually be able to send mail to it.
I also don't want to do email confirmation, though, where the user would have to click a link from an email to register. I just want it to verify on the spot.
You can do all the validation you want, but in the end the best and only way is to send an email with a verification link.
Also, because there is a huge amount of valid and odd emails that you would think aren't, the idea is generally to have fairly loose validation. Take a look here for all sorts of interesting emails.
You will need to do a DNS lookup on the MX record for the domain, then make sure that mx domain is contactable. I think that is about as close as you can get.
You might also consider letting a 3rd party do the validation for you - e.g. implement Google OAuth as a method of registration for your site.
In case of Laravel (you've mentioned it as a tag for the question) I suggest you to use such a Laravel's native feature as Validation: Laravel 3 / Laravel 4.
Below is how I use it in POST controller:
// Rules for form validation
$rules = array(
'email' => array('required', 'email', 'unique:users,email'), // Email is required and should satisfy E-mail format and it should be unique for table users.
);
// Form validation
$validation = Validator::make(Input::all(), $rules);
if($validation->fails()) {
// Flash validator with input values and errors to some controller
Former::withErrors($validation);
return Redirect::to_action('some.controller')
->with_input()
->with_errors($validation);
}
}
In general PHP usage case you can check it using PHP's native function like this:
filter_var($email, FILTER_VALIDATE_EMAIL)
I have a bit of a problem with my PHP form validation that I could use some help with.
I got an optional field which should be validated only if the user fills it, otherwise the form should be processed as normal. Here's the validation for the field:
if (!preg_match("/(0?\d|1[0-2]):(0\d|[0-5]\d) (AM|PM)/i", '$start')) :
$errors->add('submit_error', __('<strong>ERROR</strong>: The time is incorrect', 'appthemes'));
endif;
Might be simple, but at the moment I just can't get my head around how can I bypass the validation if the field is left empty. Any ideas?
if(!empty($your_field) && !preg_match(...))
PHP tests if the field is null before testing the regex.
If the field is null PHP will jump to the next instruction.
Wrap the rest of your code inside of this, it will only trigger if $start isn't empty,
if (trim($start)) {
// put other code in here
}
Assuming your form data stored in $start :
if ($start && !preg_match("/(0?\d|1[0-2]):(0\d|[0-5]\d) (AM|PM)/i", '$start')) :
$errors->add('submit_error', __('<strong>ERROR</strong>: The time is incorrect', 'appthemes'));
endif;
Have you tried something like this:
if (!empty($_POST['field_name'])) {
if(!preg_match("/(0?\d|1[0-2]):(0\d|[0-5]\d) (AM|PM)/i", '$start')) :
$errors->add('submit_error', __('<strong>ERROR</strong>: The time is incorrect', 'appthemes'));
}
It will first look at the state of the field then move to the validation if required.
EDIT
Sorry, just realised there is an optimal way being:
if(!empty($start) && !preg_match("/(0?\d|1[0-2]):(0\d|[0-5]\d) (AM|PM)/i", '$start')) :
$errors->add('submit_error', __('<strong>ERROR</strong>: The time is incorrect', 'appthemes'));
endif;
Why the !empty($start)? Because it is using the standard PHP function that defines if the value is present or not. Not 100% required but is best practice to use the empty() function when determining if a value exists or not.
I'm trying to create a fairly simple form that has a few checkboxes and input fields and a textarea. Nothing is required by itself; however, if 'A' checkbox is checked, then 'A' input field is required (and so on for the couple other checkboxes I have).
I have the above functionality in place, but I'm having a tough time figuring out how to have an error returned if the form is submitted blank (since nothing is required by default).
Does anyone know of an easy-ish solution for this? It seems like it should be so simple...
Thanks
I assume that your using the form_validation class..
You will need to write a callback that does something like this:
function _checking()
{
if (isset($_POST['a_checkbox']))
{
if (empty($_POST['a_text_field']))
{
$this->form_validation->set_message('_checking', 'this should not be empty');
return FALSE;
}
return TRUE;
}
}
I hope this is what you are looking for..
Just check if $_POST-array is empty, except for your submitbutton?