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.
Related
I'm trying to create a user registration script for my website, and although my current code works, I'm wondering if the syntax is correct, and if there are modifications that I need to make to increase security and avoid mistakes.
My registration form has multiple fields, some of which cannot be null (ex. email and password), and some of which can be null (ex. birthdate). Each field has jquery / client-side validation, and the form cannot be submitted until the required fields are set. After checking if the registration form has been submitted, I'm saving up the information in different variables as follows:
$email=isset($_POST['email']) ? $database->escape($_POST['email']) : "";
$birthdate=isset($_POST['birthdate']) ? $database->escape($_POST['birthdate']) : "";
I know I need to escape the information before saving, which is what the escape function does in this case, but other than that, I'm wondering if my approach/logic is wrong?
Should I be checking both isset and empty for each field, or should I have a different approach for fields that can be null and those that can't?. Ex:
$email=isset($_POST['email'])&&!empty($_POST['email']) ? $database->escape($_POST['email']) : "";
Or is checking for !empty enough in such case?
$email=!empty($_POST['email']) ? $database->escape($_POST['email']) : "";
Before the sql insertion I'm checking if(empty($email)) in which case the registration doesn't go through, so I'm confused as to if I do need both the isset and empty checks when first retrieving the information and saving it to variables.
Thanks for any help/advice you can give me on this topic. I graduated 2 years ago and have mostly worked on frontend web design, I learned php and mysql in school during my last two years, but nowhere in my notes or practice files do I see a mention of isset to check if a value is received, they all save the post or get straight to the variable, and there was no mention of mysqli or pdo, just mysql which I know has been deprecated (and apparently there were warnings of this happening before they even thought me about it). Looks like my teachers were behind on this practices, I've learned so much about php and mysqli in the last few days only while working on this project, I'm still confused by a lot of things although I think I'm getting the hang of it.
You must only use empty() for mandatory fields then escape all fields. Don't forget to hash passwords!
If you use isset and you create registration:
<?php
$login = $_POST['login'];
$pass = $_POST['pass'];
$pass2 = $_POST['pass2'];
$age = $_POST['age'];
if(isset($login)){
if(!empty($login) AND !empty($pass) AND !empty($pass2) AND !empty($age) AND $pass == $pass2){
// Check lenght of variables...
// AND Check login in base (1 login == 1 account) :D
} else {
echo "Please check empty variables!";
}
}
?>
Good Luck!
I have several input fields and I want it to submit when there is only one field with entered values and the others are empty (updating user data). I worked by now with isset() but this only sends the form when every field is filledout:
if (isset
($_POST['submit']) AND
($_POST['firstname']) AND
($_POST['lastname']) AND
($_POST['address']) AND
($_POST['ZIP']) AND
($_POST['phonenumber']) AND
($_POST['mail']) AND
($_POST['group'])
)
Later on I check in the mail template (another file) if there is a value and wheter to show it in the mail or not:
{if !empty($firstname)}{translate text='First Name'}: {$firstname|escape} {/if}
Is my idea ok or is there an easier way to solve this?
The first if statement is in conflict with your requirements; you are requiring all fields to be filled in by using the AND operation - use OR and it will work with any single field value.
Validation should/could also be performed on the page itself by using javascript as Matt recommends.
To ensure that only one field is set do the following you could count the number of entries in _POST
if(count($_POST) == 1 AND
(isset($_POST['submit']) OR
isset($_POST['firstname']) OR
isset($_POST['lastname']) OR
isset($_POST['address']) OR
isset($_POST['ZIP']) OR
isset($_POST['phonenumber']) OR
isset($_POST['mail']) OR
isset($_POST['group'])
))
Either way it's not a very elegant way of doing this - but it will work.
If you want only one value from a field which is set to required (if possible, use javascript, or HTML5 has a required attribute for that), simply ignore other values from other fields:
<?php
if ( isset( $_POST['submit'] ) ) {
$wanted_value = addslashes( strip_tags( $_POST['input_name'] ) );
// preventing from sql injection
// ignore other values
// and start manipulating it
}
?>
One suggestion would to be to use javascript and your onSubmit function on the form in addition to a serverside check. Using that, you can check all of your fields, and alert the user to fill some in BEFORE it gets submitted to the server.
In a javascript function check all of your inputs for a correct input, and allow the data to be sent to the server if it is all filled in correctly, or pop up an alert saying what else needs to be done before it can be submitted.
Doing this check strictly serverside will require a server request to check the input every time, as opposed to having the client check it, and submit it only if everything is correct.
Assuming you want to send the form if there's at least one field that's filled, you could use the following if-statement:
if(count($_POST) > 1)
This allows you to submit the form and have at least one field filled, but you can also have more fields filled.
If you want to send the form only if there's one field that's filled, you could change the above if-statement to the following:
if(count($_POST) == 2)
This allows you to have only one field filled.
The reason I use "== 2" is because the submit-button is also something that will be sent.
If you want to allow all the fields to be empty, you can use the following if-statement:
if(count($_POST) > 0)
This would allow you to submit the button and leave all the other fields empty.
The reason this works is because $_POST is a pre-defined array-variable.
To ensure that the user only uses fields that you want them to use and still keep the code clean, you can use an array.
Do the following:
$allowed_fields = array('firstname','lastname','address','ZIP','phonenumber','mail','group');
And then just add the following to your if-statement:
if(count($_POST) == 2 AND in_array($allowed_fields, $_POST))
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
}
I would like to do something roughly analogous (but not exactly identical) to the following: I want to create a Person content type, which has an SSN field. I would like to store the SSN field as an integer, but allow the user to input the number as 123-45-6789. This means that before validation triggers, stating that "123-45-6789" is invalid input, I would like to remove the dashes and treat this as an integer.
I've tried to use both a #value_callback function, as well as a non-default validation function. The problem then is that although I can force the value to be validated, the unchanged value is what is passed to the db for insertion, which fails. In example, this means that although I can force "123-45-6789" to be recognized by Drupal as "123456789", the database is still being passed "123-45-6789", which of course fails.
The one obvious solution would be altering this via client side javascript, before the value is even submitted to the webserver. I would strongly prefer to avoid this route.
Apologies if I've misunderstood but you should just be able to do something like this:
function my_validation_handler(&$form, &$form_state) {
if (passes_ssn_validation($form_state['values']['SSN'])) {
// Changing the value in $form_state here will carry on over to the submission function
$form_state['values']['SSN'] = convert_to_db_format($form_state['values']['SSN']);
}
else {
form_set_error('SSN', 'The SSN was invalid');
}
}
Then you'd attach that validation function using $form['#validate'][] = 'my_validation_handler' in either your form build or form_alter function.
Hope that helps
you should use hook_node_presave(). It allows you to change the values of different fields before they are inserted to the database. Here's the official documentation:
http://api.drupal.org/api/drupal/modules--node--node.api.php/function/hook_node_presave/7
Hope this can help :)
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?