I need to validate just one field (called 'Instance') to accept lowercase ASCII letters and numbers only, the first character also has to be a letter not a number. It will accept uppercase characters but we will need it to lowercase them on input. So if someone uses the instance name McDonalds it will be lowercased to mcdonalds (not just with CSS). Spaces are not allowed either.
Is this possible with CF7? If so please explain how.
I've already tried this custom validation method but even with the preset custom validation in the file it was just displaying the field shortcode rather than the field itself.
Thanks
From contactform7.com on Custom Validation → Validation as a Filter:
In Contact Form 7, a user-input validation is implemented as a filter
function. The filter hook used for the validation varies depending on
the type of form-tag and is determined as: wpcf7_validate_ + {type of
the form-tag}. So, for text form-tags, the filter hook
wpcf7_validate_text is used. Likewise, wpcf7_validate_email* is used
for email* form-tags.
Let’s say you have the following email fields in a form:
Email: [email* your-email]
Confirm email: [email* your-email-confirm]
The following listing shows code that verifies whether the two fields
have identical values.
add_filter('wpcf7_validate_email*', 'custom_email_confirmation_validation_filter', 20, 2);
function custom_email_confirmation_validation_filter($result, $tag) {
$tag = new WPCF7_FormTag($tag);
if ('your-email-confirm' == $tag->name) {
$your_email = isset($_POST['your-email']) ? trim($_POST['your-email']) : '';
$your_email_confirm = isset($_POST['your-email-confirm']) ? trim($_POST['your-email-confirm']) : '';
if ($your_email != $your_email_confirm) {
$result->invalidate($tag, "Are you sure this is the correct address?");
}
}
return $result;
}
Two parameters will be passed to the filter function: $result and
$tag. $result is an instance of WPCF7_Validation class that manages a
sequence of validation processes. $tag is an associative array
composed of given form-tag components; as you saw in the previous
recipe, you can use WPCF7_FormTag class to handle this type of data.
Look through the inside of the filter function. First, check the name
of the form-tag to ensure the validation is applied only to the
specific field (your-email-confirm).
The two email field values are then compared, and if they don’t match,
$result->invalidate() will be called. You need to pass two parameters
to the invalidate() method: the first parameter should be the $tag
variable, and the second parameter is the validation error message
that you want the field to display.
Lastly, don’t forget to return the $result.
// Add custom validation for CF7 form fields
function is_company_email($email){ // Check against list of common public email providers & return true if the email provided *doesn't* match one of them
if(
preg_match('/#gmail.com/i', $email) ||
preg_match('/#hotmail.com/i', $email) ||
preg_match('/#live.com/i', $email) ||
preg_match('/#msn.com/i', $email) ||
preg_match('/#aol.com/i', $email) ||
preg_match('/#yahoo.com/i', $email) ||
preg_match('/#inbox.com/i', $email) ||
preg_match('/#gmx.com/i', $email) ||
preg_match('/#me.com/i', $email)
){
return false; // It's a publicly available email address
}else{
return true; // It's probably a company email address
}
}
function your_validation_filter_func($result,$tag){
$type = $tag['type'];
$name = $tag['name'];
if('yourid' == $value){ // Only apply to fields with the form field name of "company-email"
$the_value = $_POST[$name];
if(!is_company_email($the_value)){ // Isn't a company email address (it matched the list of free email providers)
$result['valid'] = false;
$result->invalidate( $tag, wpcf7_get_message( 'invalid_email' ));
}
}
return $result;
}
add_filter( 'wpcf7_validate_email', 'your_validation_filter_func', 10, 2 );
// Email field or contact number field
add_filter( 'wpcf7_validate_email*', 'your_validation_filter_func', 10, 2 ); // Req. Email field or contact number
I had a similar issue for validating name fields, I added the following code in my functions.php, you could customize it by changing the regex
function my_wpcf7_validate_text( $result, $tag ) {
$type = $tag['type'];
$name = $tag['name'];
$value = $_POST[$name] ;
if ( strpos( $name , 'name' ) !== false ){
$regex = '/^[a-zA-Z]+$/';
$Valid = preg_match($regex, $value, $matches );
if ( $Valid > 0 ) {
} else {
$result->invalidate( $tag, wpcf7_get_message( 'invalid_name' ) );
}
}
return $result;
}
add_filter( 'wpcf7_validate_text*', 'my_wpcf7_validate_text' , 10, 2 );
add_filter( 'wpcf7_messages', 'mywpcf7_text_messages' );
function mywpcf7_text_messages( $messages ) {
return array_merge( $messages, array(
'invalid_name' => array(
'description' => __( "Name is invalid", 'contact-form-7' ),
'default' => __( 'Name seems invalid.', 'contact-form-7' )
)
));
}
Please use this wordpress plugin
Jquery Validation For Contact Form 7
https://wordpress.org/plugins/jquery-validation-for-contact-form-7/
You can add your own custom validation for a form field input by using the add_filter function.
For adding a custom validation for a textarea field you can add the following inside functions.php file in the root directory of your theme.
add_filter( 'wpcf7_validate_textarea*', 'custom_textarea_validation_filter', 1, 2 );
function custom_textarea_validation_filter( $result, $tag ) {
$tag = new WPCF7_Shortcode($tag);
$result = (object)$result;
$name = 'project-synopsis';
if ( $name == $tag->name ) {
$project_synopsis = isset( $_POST[$name] ) ? trim( wp_unslash( (string) $_POST[$name] ) ) : '';
if ( empty( $project_synopsis ) ) {
$result->invalidate( $tag, "Please write a quick project synopsis." );
}
}
return $result;
}
For me the trick was to cast the $result parameter to an object, because the invalidate method that is used to add the error message didn't work before casting.
Try this plugin. It's allow to set custom validation message for each field in free version.
URL : https://wordpress.org/plugins/cf7-custom-validation-message/
Related
I’d like to update what users insert into 3 specific xprofile fields and store it to the database using sanitize_key (force letters lowercase, remove special characters besides "-" and "_"). The values change the way I want to temporarily when I echo them out, but don't store in the database.
Would really appreciate your help! Here's what I have so far
In my functions.php:
function expertise_tag_functions_before_save() {
global $bp;
foreach ($_REQUEST as $field => $value) {
if ($field == ‘field_24’ || $field == ‘field_26’ || $field == ‘field_27’) {
$value = sanitize_key( $value );
$field_label = str_replace(‘field_’, ”, $field);
xprofile_set_field_data($field_label, $user_id, $value);
}
}
};
add_action( ‘xprofile_data_before_save’, ‘expertise_tag_functions_before_save’, 10);
I've tried switching out ‘xprofile_data_before_save for ‘xprofile_data_after_save’ but it still doesn't work.
Your changes are probably being overwritten after the filter hook runs.
You are directly updating the field. You should be changing the submitted profile data.
This is the filter hook which includes access to that data:
do_action_ref_array( 'xprofile_data_before_save', array( $this ) );
So try:
function expertise_tag_functions_before_save( $data ) {
// make your changes to field values in $data
}
On my WordPress page I have created a shortcode function which gets a parameters from the URL of the post. So, I have created this simple function and added the following code to the theme's file function.php:
function getParam($param) {
if ($param !== null && $param !== '') {
echo $param;
} else {
echo "Success";
}
}
add_shortcode('myFunc', 'getParam');
And I know I have to add this shortcode to posts and pages using (in my case) [myFunc param=''].
Usually, I would get the value of the parameter from the URL using <?php $_GET['param'] ?>, but in this case I don't know how to send this PHP code to the shortcode function.
For example, I doubt I can write [myFunc param=$_GET['param']].
A shortcode like this:
[myFunc funcparam="param"]
Is not needed here, unless the called parameter is changing with the posts.
Let's say you have this URL:
http://example.com?param=thisparam
To get the value of 'param' by using the shortcode described above, your function in functions.php should look something like this:
function sc_getParam() {
// Get parameter(s) from the shortcode
extract( shortcode_atts( array(
"funcparam" => 'funcparam',
), $atts ) );
// Check whether the parameter is not empty AND if there is
// something in the $_GET[]
if ( $funcparam != '' && isset( $_GET[ $funcparam ] ) ) {
// Sanitizing - this is for protection!
$thisparam = sanitize_text_field( $_GET[ $funcparam ] );
// Returning the value from the $_GET[], sanitized!
return $thisparam;
}
else {
// Something is not OK with the shortcode function, so it
// returns false
return false;
}
}
add_shortcode( 'myFunc', 'sc_getParam' );
Look up these references:
WordPress Shortcodes: A Complete Guide - tutorial on creating shortcodes
Validating Sanitizing and Escaping User Data - sanitizing
If you need get the parameters you can:
function getParam($arg) {
if (isset($arg) &&
array_key_exists('param', $arg ) &&
$arg['param'] != '')
{
return $_GET[$arg['param']]; // OR get_query_var($arg['param']);
}
else
return "Success";
}
add_shortcode('name', 'getParam');
Do it this way:
function getParam($data)
{
$var = $_GET[$data['param']];
if ($var !== null && $var !== '')
{
echo "True: " . $var;
}
else echo "False: " . $var;
}
And call it by: [myFunc param=whatever]
You shouldn't call a function in the shortcode.
For better understanding, I changed your code just a little bit, but beware this is not secure and clean.
For a project with Laravel 4.1 I have a little UI issue I'd like to solve.
Some inputs make an ajax call to laravel on blur and that works fine. It simply sends it's value. In laravel I then check with the validator.
public function validate() {
if(Request::ajax()) {
$validation = Validator::make(Input::all(), array(
'email' => 'unique:users|required|email',
'username' => 'required'
));
if($validation->fails()) {
return $validation->messages()->toJson();
}
return "";
}
return "";
}
Although this works, the json string also contains fields I have no need to check. To be precise this is the feedback I get:
{"email":["The email field is required."],"username":["The username field is required."]}
But seeing it is on blur I only want the one I'm actually checking in return. So if i'm blurring email I want a return of:
{"email":["The email field is required."]}
Now I know it's obviously because my array contains multiple fields, but I don't feel like writing a complete validation for each possible input I ever make.
My question is: can I somehow only get a return of the post values that are actually posted, even though the value might be null and not get rest of the array back.
Try this (untested, feel free to comment/downvote if it doesn't work) :
// Required rules, these will always be present in the validation
$required = ["email" => "unique:users|required|email", "username" => "required"];
// Optional rules, these will only be used if the fields they verify aren't empty
$optional = ["other_field" => "other_rules"];
// Gets input data as an array excluding the CSRF token
// You can use Input::all() if there isn't one
$input = Input::except('_token');
// Iterates over the input values
foreach ($input as $key => $value) {
// To make field names case-insensitive
$key = strtolower($key);
// If the field exists in the rules, to avoid
// exceptions if an extra field is added
if (in_array($key, $optional)) {
// Append corresponding validation rule to the main validation rules
$required[$key] = $optional[$key];
}
}
// Finally do your validation using these rules
$validation = Validator::make($input, $required);
Add your required fields to the $required array, the key being the field's name in the POST data, and the optional fields in the $optional array - the optional ones will only be used if the field exists in the submitted data.
You can also use Laravel requests in a much cleaner way
public function rules(){
$validation = [];
$input = Request::all();
if (array_key_exists('email', $input)) {
$validation['email'] = 'unique:users|required|email';
}
if (array_key_exists('username', $input)) {
$validation['username'] = 'required|min:6';
}
return $validation;
}
I found it. It's going to be something like this:
if(Request::ajax()) {
$arr = array();
$arr['email'] = 'unique:users|required|email';
$arr['username'] = 'required|min:6';
$checks = array();
foreach($arr as $key => $value) {
if(Input::has($key)) {
$checks[$key] = $value;
}
}
if(count($checks)) {
$validation = Validator::make(Input::all(), $checks);
if($validation->fails()) {
return $validation->messages()->toJson();
}
}
return "ok";
}
return "";
I'm pretty new to Silex and Symfony and I'm trying to create a form with the symfony Form component. That's working fine, but whet it comes to validation/sanitization I'm not sure how to do it.
Of course I know the $app->escape($data) method, but it doesn't seem to fit my needs.
I'd like to escape html tags from the submitted data before I call the $form->isValid() method. I don't want to invalidate texts with html tags, only escape/remove them from the text then validate the gained values.
So basically I want to give the escaped values to the form instead of the originals or use.
My problem is that I'd like to show the error messages only if the submitted text is empty after removing the html tags.
I thought about to write a custom constraint - as I didn't find anything about html validation in the package - but in that case I had to filter/escape two times, first in the validation then before saving the data.
I'd like to achieve something like this:
if ($request->getMethod() == 'POST') {
$comment = $request->get('comment');
if($comment) {
foreach($comment as &$value) {
$value = $app->escape($value);
}
$cleared = new Request(array(), array('comment' => $comment));
$form->bindRequest($cleared);
if ($form->isValid()) {
var_dump($form->getData());
}
}
}
Thanks.
$app->escape() is just a shortcut for htmlspecialchars(), you have to use strip_tags() function to remove html tags.
My problem is that I'd like to show the error messages only if the
submitted text is empty after removing the html tags.
$form->get('FILED_NAME')->addError(new Form\FormError('ERROR'));
for example :
if ($request->getMethod() == 'POST') {
$comment = $request->get('comment');
if($comment) {
$emptyCM = false;
foreach($comment as &$value) {
$value = strip_tags($value);
if (empty($value)) $emptyCM = true;
}
if ($emptyCM)
$form->get('comment')->addError(new Form\FormError('my custom error message'));
$cleared = new Request(array(), array('comment' => $comment));
$form->bindRequest($cleared);
if ($form->isValid()) {
var_dump($form->getData());
}
}
}
If you want to pre-sanitize your all your data before it goes into the form, you can use a before filter, either for all routes or for specific routes.
The following example strips all tags from string parameters from GET and POST. If your parameters are arrays (like in your initial example), you'd need to add another if branch. If your parameters are deeply nested, you need a recursive function for filtering.
$app->before( function( Request $request ) {
foreach ( [ $request->request, $request->query ] as $parameterBag ) {
foreach ( $parameterBag->keys() as $key ) {
if ( is_string( $parameterBag->get( $key ) ) ) {
$parameterBag->set( $key, strip_tags( $parameterBag->get( $key ) ) );
}
}
}
}, Application::EARLY_EVENT );
I need a php validator class that validates user inputs.
I want it to be able to accept an assoc array of fields => values like:
array(
"username" => "Alex",
"email_address" => "###3423£alex#my.mail.com"
);
and then return an array of errors like this:
array(
"username" => "",
"email_address" => "Invalid Email Address"
);
But I'm really struggling on HOW the hell I'm going to do this!
I've read countless pages on PHP validators and read that the best way to do this is with the strategy pattern. But i dont know how??
Like... This is what I've got so far:
class Validator {
private
$_errors,
$_fields,
static private $_map = array (
"firstname" => "name",
"surname" => "name",
"agency_name" => "name",
"agency_office" => "name",
"username" => "username",
"email_address" => "email_address",
);
public function __construct( array $fields ) {
$this->_fields = $fields;
}
public function validate() {
foreach ( $this->_fields as $field => $value ) {
if ( method_exists( __CLASS__, self::$_map[$field] ) ) {
if ( in_array( $field, self::$_map ) ) {
$this->{self::$_map[$field]}( $field, $value );
}
}
else {
die( " Unable to validate field $field" );
}
}
}
public function get_errors() {
return $this->_errors;
}
private function name( $field, $value ) {
if ( !preg_match( "/^[a-zA-Z]{2,50}$/", $value ) ) {
$this->errors[$field] = "Invalid. Must be 2 to 50 alphanumerical characters";
}
}
private function username( $field, $value ) {
if ( !preg_match( "/^[a-zA-Z0-9_\-]{10,50}$/", $value ) ) {
$this->errors[$field] = "Invalid. Must be 10 to 50 characters. Can contain digits, characters, _ (underscore) and - (hyphen)";
}
}
private function password( $field, $value ) {
if ( !preg_match( "/^[a-zA-Z0-9\.\-]{8,30}$/", $value ) ) {
$this->_errors[$field] = "Invalid. Must be 8 to 30 characters. Can contain digits, characters, . (full stop) and - (hyphen)";
}
}
private function email_address( $field, $value ) {
if ( !filter_var( $value, FILTER_VALIDATE_EMAIL ) ) {
$this->_errors[$field] = "Invalid Email Address";
}
}
}
The problems with this is, it doesn't even consider database connections for like, already registered usernames,
Also is doesn't match passwords
I've just got coders block at the moment and its destroying me on the inside :(
Can anybody give a an explaination of the classes required and functions each class will need to do?
I really need the inputs and outputs to be in the format already explained though!
Thankyou Very Much Internet People!
As a part of the my MVC I have solved the same problem. I could give you a listing, but in a few lines try to describe how.
I got 3 base classes Form, Validator, Field, each of object of this classes configuring through one YAML file, structured somehow like this:
name: // field name
i18n: [ ru, en ] // is the field i18n
field:
class: Base // class to use for field
options: { specific_save: true } // options from available (defined in class)
attributes: { } // attributes, for HTML rendering
validator:
class: String // Class to validate with
options: { required: true, max: 100 } // options for validator
So, lets start with Form, when object is constructing the form takes the YAML file described above, and due to that configuration creates fields. Something like this:
// Imlement this function to configure form;
foreach ($this->_config as $f => $c)
{
$class = '\\Lighty\\Form\\Field\\' . (isset($c['field']['class']) && $c['field']['class'] ? $c['field']['class'] : 'Base');
$o = isset($c['field']['options']) && is_array($c['field']['options']) ? $c['field']['options'] : array();
$a = isset($c['field']['attributes']) && is_array($c['field']['attributes']) ? $c['field']['attributes'] : array();
$field = new $class($this, $o, $a);
$field->setName($f);
$class = '\\Lighty\\Form\\Validator\\' . (isset($c['validator']['class']) && $c['validator']['class'] ? $c['validator']['class'] : 'Base');
$o = isset($c['validator']['options']) && is_array($c['validator']['options']) ? $c['validator']['options'] : array();
$m = isset($c['validator']['messages']) && is_array($c['validator']['messages']) ? $c['validator']['messages'] : array();
$field->setValidator($validator = new $class($field, $o, $m));
if (isset($this->_options['default'][$f]))
{
$field->setValue($this->_options['default'][$f]);
}
if (isset($c['i18n']))
{
if (is_array($c['i18n']))
{
$field->setCultures($c['i18n']);
}
$field->setI18n((bool) $c['i18n']);
}
$this->addField($field);
So, now we have form with fields and validator for each field, then to validate I use this mechanism:
Form goes through each field, calling validate() method,
Field (got the binded value) call validate($value) method of binded Validator, passing the stored value. Inside this method Validator calls the validateOption() method, in which there is a simple switch for each options, for example:
switch ($o)
{
case 'required':
$valid = $state && trim($value) != '' || !$state;
break;
default:
return \warning(sprintf('Undefined validator option "%s" in %s validator class', $o, get_class($this->getField()->getValidator())), null);
}
Here you can see validating on required option. If I need more validators, I extend class of the Base validator, defined few more options, and redefine validateOption(), where in default statement of the option's switch put parent::validateOption(). So specified options validates in new class, and old one in base validator Class.
If there any questions... You're welcome.