Codeigniter Email REGEX - regex

What is the regular expression used by codeigniter to validate email addresses? I plan on using the same regex on the javascript part of the form validation, so that the regexes won't collide, e.g. xy##spic7.com might pass in the javascript part, but it won't pass in the php part )

You could have looked at the source code yourself in the same amount of time it took to post this question but, either way, this is the method CI uses to validate emails, straight from system/libraries/Form_validation.php:
/**
* Valid Email
*
* #access public
* #param string
* #return bool
*/
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}

Maybe the best solution is calling email helper and checking email validity:
$this->load->helper('email');
if (valid_email('email#somesite.com')) echo 'email is valid';

Related

Regex email vaildation in Zend

I'm using email validation of zend framework and when I give email address as abcde#gester.tech and it responded with invalid validation. Then I modifed the validation as below.
$emailValidator= new Validator\EmailAddress(Validator\Hostname::ALLOW_DNS | Validator\Hostname::ALLOW_LOCAL);
$emailRegex= new Validator\Regex(
array(
'pattern' => '/^(?:(?:[^<>()\[\]\\.,;:\s#"]+(?:\.[^<>()\[\]\\.,;:\s#"]+)*)|(?:".+"))#(?:(?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/',
'messages'=>array(
'regexNotMatch'=>'Make sure your email pattern is correct'
)
)
);
$emailInp->getValidatorChain()->addValidator($emailValidator)->addValidator($emailRegex);
Now am able to pass the email address (abcde#gester.tech) with out validation error. But if I give the input as abcde#gester it also take as valid input. But I want to restrict that and I think this can be implemented by adding regex to this validation. May I know how to implement that.
$emailValidator= new Validator\EmailAddress(
Validator\Hostname::ALLOW_DNS |
Validator\Hostname::ALLOW_LOCAL);
$emailRegex= Validator\Regex(array('pattern' => '/^(?:(?:[^<>()\[\]\\.,;:\s#"]+(?:\.[^<>()\[\]\\.,;:\s#"]+)*)|(?:".+"))#(?:(?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'));
$emailInp->getValidatorChain()->addValidator($emailValidator->addValidator($emailRegex));
There is a Regex Validator support in Zend framework which facilitates matching the user-defined regex pattern. There is a pattern option which sets the regular expression pattern for the given validator.
You can use it to match the user-defined validator i.e. the pattern that suits your need.
SYNTAX:
$validator = new Zend\Validator\Regex(array('pattern' => '/your_desired_regex_pattern_here/'));
For matching the valid email address that suits your need you can fill in the pattern with available regex validators for email addresses. Also as per the Zend docs; the regex validator uses PCRE(php) syntax, so you can use PCRE regex flavor.
A sample example:
$validator = new Zend\Validator\Regex(array('pattern' => '/^(?:(?:[^<>()\[\]\\.,;:\s#"]+(?:\.[^<>()\[\]\\.,;:\s#"]+)*)|(?:".+"))#(?:(?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'));
$validator->isValid("abcde#gester.tech"); // returns true
$validator->isValid("abcde#gester"); // returns false
$validator->isValid("Someemail#someDomain.com"); // returns true
If you want to chain multiple validators on a single input data you can also use the below syntax:
$validatorChain = new Zend_Validate();
$validatorChain->addValidator(
new Zend\Validator\Regex(array('pattern' => '/^(?:(?:[^<>()\[\]\\.,;:\s#"]+(?:\.[^<>()\[\]\\.,;:\s#"]+)*)|(?:".+"))#(?:(?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'))
->addValidator(new Zend_Validate_Alnum()); // Second validator...You can chain multiple
if ($validatorChain->isValid($input_email)) {
// email passed validation
} else {
// email failed validation; print reasons
foreach ($validatorChain->getMessages() as $message) {
echo "$message\n";
}
}
You can find the demo of the above regex in here.
Reference: The regex for validating email address is taken from this answer.

DialogFlow/Api.AI inline editor regex for email validation

https://github.com/dialogflow/fulfillment-regex-nodejs
shows an easy way to perform a regex validation, however I haven't succeeded in creating one for email addresses.
from the original regex i changed the pattern to [^\s]*#[a-z0-9.-]
changed the dialogflow parameter to email with $email and kept the rest the same.
function validateEmployeeID (agent) {
// get the employee ID parameter from the request header received from Dialogflow
let email = agent.parameters.email;
let pattern = /[^\s]*#[a-z0-9.-]/;
if (email.match(pattern) !== null)
{ agent.add(`Email is wrong, please provide a valid email address.`); }
else { agent.add(agent.request_.body.queryResult.fulfillmentText); }
}
If you just want to create a regex for email validation then there are lots of links available.
You may try the below one from here.
/[A-Z0-9._%+-]+#[A-Z0-9-]+.+.[A-Z]{2,4}/igm
and test it online here
after some research, I have had success with this regex
^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$
more info here for others interested; https://blog.dialogflow.com/post/validate-entities-using-regular-expressions-in-fulfillment/

DataAnnotation TextArea Multiple Emails

I am using MVC 3.
I have a text area in which user can enter multiple emails addresses. Emails can be separated by a comma and a space. User may hit enter in the box as well.
Is there an attribute that can handle this scenario?
I am using regular expression to check for the characters and it is failing for "abc#abc.com, tyz#tyz.com"
Here is my regular expression:
[RegularExpression(#"([a-zA-Z0-9 .#-_\n\t\r]+)", ErrorMessage = ValidationMessageConstants.EmailAdressInvalid)]
What am i missing here? This regular expression is off the following post:
DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view
Out of the box, .NET 4.5 has the System.ComponentModel.DataAnnotations.EmailAddressAttribute found in the System.ComponentModel.DataAnnotations assembly, but this is limited to validating just one email address. Hence, if you have a model that accepts delimitted email address and you decorate the property with this attribute, it will fail since it will treat the entire string as one email.
What I've done is create an extended emailaddress attribute that validates the delimited email addresses:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class EmailAddressExAttribute : DataTypeAttribute
{
#region privates
private readonly EmailAddressAttribute _emailAddressAttribute = new EmailAddressAttribute();
#endregion
#region ctor
public EmailAddressExAttribute() : base(DataType.EmailAddress){ }
#endregion
#region Overrides
/// <summary>
/// Checks if the value is valid
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public override bool IsValid(object value)
{
var emailAddr = Convert.ToString(value);
if (string.IsNullOrWhiteSpace(emailAddr)) return false;
//lets test for mulitple email addresses
var emails = emailAddr.Split(new[] {';', ' ', ','}, StringSplitOptions.RemoveEmptyEntries);
return emails.All(t => _emailAddressAttribute.IsValid(t));
}
#endregion
}
You can now decorate any string property with this new extended attribute to validate delimited email addresses. You can update the delimiters to include any special characters you want to use as well.
Hope this helps!
You not stating what the question is, so I will have to assume from your answer that data annotations aren't working as you would expect.
Having that assumption in mind, its very easy why is it not working: data annotation operates on the entire field, text area in your case. It will work as expected if you have only one email. Since you have multiple emails in that field, separated by comma or space, the field in its entirety doesn't reflect what data annotation for email prescribes and fails.
To answer your numbered questions:
No, there is no out of the box
The regular expression you using doesn't account for multiple emails, but one. The solution in your case will be either to
Data annotation using RegEx for multiple emails separated as you'd like or
Have custom validation attribute doing it for you
Following the links above you will see very good examples of "how to" and hopefully get you going in the right direction.
Hope this helps, please let me know if not.

Joomla 2.5 content plugin

I'm trying to deploy a simple plugin to a Joomla 2.5 installation. The code in the plugin that is outside the class declaration runs and adds the two script tags to the head. However, the code within does nothing. I can't change the $article->title or $article->text. I've copy and pasted, verbatim from different articles, but everything seems to talk only about 1.5. The 1.7 stuff that I do find only mentions changing onPrepareContent to onContentPrepare. Neither seems to do anything. I would appreciate any help!
<?php
// No direct access.
defined( '_JEXEC' ) or die( 'Restricted access' );
class plgContentPicasaGallery extends JPlugin
{
/**
*
* #param string The context of the content being passed to the plugin.
* #param mixed An object with a "text" property.
* #param array Additional parameters.
* #param int Optional page number. Unused. Defaults to zero.
* #return boolean True on success.
*/
public function onContentBeforeDisplay($context, &$article, &$params, $page = 0)
{
if (is_object($article)) {
$article->text = "omfg, wtf?";
return true;
} else {
$article = "omfg, I'm not an object, wtf?";
return true;
}
}
}
Joomla documentation & tutorials a little bit out dated, new framework changed few things.
To find proper signatures simply look at /plugins/content/... files.
Below is proper function signature & phpdoc for onContentPrepare.
/**
* #param string The context of the content being passed to the plugin.
* #param object The article object. Note $article->text is also available
* #param object The article params
* #param int The 'page' number
*/
public function onContentPrepare($context, &$article, &$params, $page = 0)
{
...
}
My noobishness with Joomla prevailed over my good sense. I was editing the plugin files on the server and I was expecting that to update the plugin. Thanks for the help!
you can use this method
jimport('joomla.form.helper');
$urla= JRequest::getVar('id');
$urlview= JRequest::getVar('view');
if ($urlview=='article')
{}
if ($urla==10<- number id article )
{}
i know framework joomla is good but its for understanding method

redirect function in CodeIgniter 2 with PHPUnit and CIUnit

I am using PHPUnit 3.5 and CIUnit with PHING 2.4 for unit testing my CodeIgniter controller functions
The problem is when the function i tested contains a redirect() function, the testcase will stop and will not continue the execution. There is also no available error log for this.
What could be the problem for this? Do i have to download/update PHPUnit specific library?
Any suggestion would be greatly appreciated.
Thanks
Well this would be because the redirect() fn exits after doing a redirect (which is what you should be doing when you do a redirect to stop further code execution while waiting on the browser redirect).
/system/helpers/url_helper.php:
/**
* Header Redirect
*
* Header redirect in two flavors
* For very fine grained control over headers, you could use the Output
* Library's set_header() function.
*
* #access public
* #param string the URL
* #param string the method: location or redirect
* #return string
*/
if ( ! function_exists('redirect'))
{
function redirect($uri = '', $method = 'location', $http_response_code = 302)
{
if ( ! preg_match('#^https?://#i', $uri))
{
$uri = site_url($uri);
}
switch($method)
{
case 'refresh' : header("Refresh:0;url=".$uri);
break;
default : header("Location: ".$uri, TRUE, $http_response_code);
break;
}
exit; <===<<< here is the exit
}
}
The only way 'around' this is to eliminate the exit; after the redirect call.
Ref: http://codeigniter.com/user_guide/helpers/url_helper.html
I was running into this too. I needed to test that a certain function was redirecting. I ended up just asserting that the new redirecting url ended with a certain string:
#Calling the controller method
$this->ci->register();
#output the headers
$out = $this->ci->ouput->get_headers();
#check that the uri ends with where it is redirecting
$this->assertStringEndsWith('/user', (string)$out[0][0]);
Keep in mind unit tests are only for a particular method. If you need to test multiple redirects going to different controllers/methods using something like selenium, as well as unit tests for each individual method.