Regex email vaildation in Zend - regex

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.

Related

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/

Replace variable names with actual class Properties - Regex? (C#)

I need to send a custom email message to every User of a list ( List < User > ) I have. (I'm using C# .NET)
What I would need to do is to replace all the expressions (that start with "[?&=" have "variableName" in the middle and then ends with "]") with the actual User property value.
So for example if I have a text like this:
"Hello, [?&=Name]. A gift will be sent to [?&=Address], [?&=Zipcode], [?&=Country].
If [?&=Email] is not your email address, please contact us."
I would like to get this for the user:
"Hello, Mary. A gift will be sent to Boulevard Spain 918, 11300, Uruguay.
If marytech#gmail.com is not your email address, please contact us."
Is there a practical and clean way to do this with Regex?
This is a good place to apply regex.
The regular expression you want looks like this /\[\?&=(\w*)\]/ example
You will need to do a replace on the input string using a method that allows you to use a custom function for replacement values. Then inside that function use the first capture value as the Key so to say and pull the correct corresponding value.
Since you did not specify what language you are using I will be nice and give you an example in C# and JS that I made for my own projects just recently.
Pseudo-Code
Loop through matches
Key is in first capture group
Check if replacements dict/obj/db/... has value for the Key
if Yes, return Value
else return ""
C#
email = Regex.Replace(email, #"\[\?&=(\w*)\]",
match => //match contains a Key & Replacements dict has value for that key
match?.Groups[1].Value != null
&& replacements.ContainsKey(match.Groups[1].Value)
? replacements[match.Groups[1].Value]
: "");
JS
var content = text.replace(/\[\?&=(\w*)\]/g,
function (match, p1) {
return replacements[p1] || "";
});

Rails 3: validate REGEX fails if no value input

I am using the following REGEX
VALID_WEBSITE_REGEX = /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(\/.*)?$/ix
to validate a website entry with this rule:
validates :website, length: { maximum: 150 }, format: { with: VALID_WEBSITE_REGEX }
(The 150 is arbitrary).
However, when I save / update the form I get a validation error "website is invalid". How do I ensure that the 'format' section of the validation rule is processed only if there is content to process?
You can use allow_blank option for validation
:allow_blank => true
This option will let validation pass if the attribute’s value is blank?, like nil or an empty string for example.
read more:
http://guides.rubyonrails.org/active_record_validations_callbacks.html#allow_blank
Enclose the entire thing with the ? operator, e.g.
VALID_WEBSITE_REGEX = /^((http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(\/.*)?)?$/ix
If you want to allow whitespace too, then add \s* on each end, e.g.
VALID_WEBSITE_REGEX = /^\s*((http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6}(:[0-9]{1,5})?(\/.*)?)?\s*$/ix

Codeigniter Email 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';

symfony form validation clean with regex before validate with regex

I'm using Symfony 1.4 and am a little stuck regarding form validation. I have a validator like the one below:
$this->setValidator('mobile_number', new sfValidatorAnd(array(
new sfValidatorString(array('max_length' => 13)),
new sfValidatorRegex(array('pattern' => '/^07\d{9}$/'),
array('invalid' => 'Invalid mobile number.')),
)
));
That is a simple regex for matching a UK mobile phone number.
However my problem is that if someone submitted a string like this: "07 90 44 65 48 1" the regex would fail but they have given a valid number if a the string was cleaned to remove whitespace first.
My problem is that I don't know where within the symfony form framework I would accomplish this.
I need to strip everything but numbers from the user input and then use my mobile_number validator.
Any ideas would be greatly appreciated. Thanks.
You may be able to do this with a combination of standard validators, but it might well be easiest to construct your own custom validator. There is a guide to this on the symfony website: http://www.symfony-project.org/more-with-symfony/1_4/en/05-Custom-Widgets-and-Validators#chapter_05_building_a_simple_widget_and_validator
I think it should probably look something like this:
class sfValidatorMobilePhone extends sfValidatorBase
{
protected function doClean($value)
{
$value = preg_replace('/\s/','',$value);
if (
(0 !== strpos($value, '07')) ||
(13 < strlen($value)) ||
(0 !== preg_match('/[^\d]/', $value))
)
{
throw new sfValidatorError($this, 'invalid', array('value' => $value));
}
else
{
return $value;
}
}
}
Save this as lib/validator/sfValidatorMobilePhone.class.php. You could then call it as
$this->setValidator('mobile_number', new sfValidatorMobilePhone());
I don't know Symfony, so I don't know how you would go about cleaning the input. If you can do a regex-based search-and-replace somehow, you can search for /\D+/ and replace that with nothing - this will remove everything except digits from your string. Careful, it would also remove a leading + which might be relevant (?).
If you can't do a "cleaning step" before the validation, you could try validating it like this:
/^\D*07(?:\d*\d){9}\D*$/
This will match any string that contains exactly 11 numbers (and arbitrarily many non-number characters), the first two of which need to be 07.