!preg_match for email checking - preg-match

I have this command to check for valid email address. I just found out that when I try to add this to our email server (all email requests off this form are local email addresses), the email server does not allow a numeric character to start the email address/username. I have read through all the documentation for the command preg_match and cannot find how to make it fail if it starts with a numeric in the first character location. I am a newbie so any help would be appreciated.
if (!preg_match("(^[-\w\.]+#([-a-z0-9]+\.)+[a-z]{2,4}$)i", $in_email))

In php you can use following code with php filter_var function which return a boolean after filtering the variable with a specified filter condition.
if(filter_var($email,FILTER_VALIDATE_EMAIL))
{
//valid email
}
else{
//INVALID EMAIL
}
The function filter_var will return true if email is in correct format otherwise false.

Try this one;
/^[^0-9][_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/
And use as follows
$regex = '/^[^0-9][_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($regex, $email)) {
// Valid email
} else {
// Invalid email
}

If we have domains without dots this answers does not work. For this case I changed from:
/^[^0-9][_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/
To:
/^[^0-9][_a-z0-9-]+(\.[_a-z0-9-]+)*#([a-z0-9-]{2,})+(\.[a-z0-9-]{2,})*$/
Update: The user #Toto saw correctly one problem with regex that can start with any chars instead off numeric. And example like: #-----.--.---.----#-- was validate. So I changed /^[^0-9] for /^[a-z] and now is correct:
/^[a-z][_a-z0-9-]+(\.[_a-z0-9-]+)*#([a-z0-9-]{2,})+(\.[a-z0-9-]{2,})*$/
And work for these use cases:
user#domain
aa#aa
aa#aa.aa
aa.aa#aa

Related

input password webchat

I have a problem with input password in webchat.I used Sample - Customize Web Chat with Password Input Activity for password input card when I enter wrong password it show a message like wrong password please try again but when i enter password out of form i need to show another message.
I used this code.
if (card.activity.type === 'message') {
if (
card.activity.from.role === 'bot' &&
(card.activity.text === getLoginMessage(this.props.language) ||
card.activity.text === getLoginRetryMessage(this.props.language))
) {
let message = card.activity.text;
if (!this.hasSubmittedPassword && (card.activity.text === getLoginRetryMessage(this.props.language))) {
message = "Please fill the form and click enter in order to complete your request.";
}
return children => (
<ConnectedPasswordInputActivity
promptMessage={message}
passwordPlaceholder={this.props.literals.password}
language={this.props.language}
handlePasswordSubmit={this.handlePasswordSubmit}
>
{next(card)(children)}
</ConnectedPasswordInputActivity>
);
}
Refer to the image please
This is hard to know for certain as there is a lot of hidden code you are referencing, however I suspect the issue is tied to your hasSubmittedPassword function and your check against it.
You are matching on
A message
From a bot
Where the text equals either the getLoginMessage or getLoginRetryMessage return value
These are passing your check (based on the attached image).
You then check against hasSubmittedPassword which (apparently) is passing and then check a second time on getLoginRetryMessage (???). This second check is unnecessary as you wouldn't be in this if statement if the first check (card.activity.text = this.getLoginRetryMessage(this.props.language) hadn't succeeded.
This can be simplified to:
if (!this.hasSubmittedPassword) {
message = "Please fill the form and click enter in order to complete your request.";
}
That being said, your use of if(!this.hasSubmittedPassword) {...} is only checking if there is a returned value or not. This function may or may not be returning the correct value, but your check doesn't care. It only wants to know IF there is a value. If your logic is setup to always return something (i.e. true, false, yes, no, try again), then it will always pass.
From what I can see, if your first three checks pass, then you will always get the secondary message.
Hope of help!

How do I prevent Grails for doing any further validations if one validation already fails?

I have a Grails command object that I'm using for updating passwords. It looks like this:
class UpdatePasswordCommand {
String password
static constraints = {
password blank: false,
nullable: false,
size: 8..64,
matches: someLongRegex
validator: { String password, command ->
if (someService.isPasswordSameAsUsername(password)) {
return 'password.invalid.sameasuser'
}
}
I left out everything that doesn't pertain to the question I'm asking.
The problem I'm running into is that, whenever this validation triggers, it will trigger ALL the validations, and the command.errors collection will have an error message for each validation failure. This means that, for example, if the user tried to use test for the password, they will get the following error messages:
* Password length must be between 8 and 64 characters.
* Password must not be the same as the user name.
* Password must contain at least one special character, uppercase letter, and digit.
In this case, if the password length is wrong, I want the validation to stop at that point. Likewise, if it's the same as the username, I don't want it to check against the regex. Is there any way I can get the Grails validation to only return the first validation failure for a particular property? Note that it's important that I only want it to stop per property, because if the user doesn't type in his confirm password, for example, I still want to display two error messages:
* Password length must be between 8 and 64 characters.
* You must enter a confirm password.
Shouldn't that be a practice to provide all the validation messages preemptively to the user so that User can rectify or take care of them in one go, instead of rectifying it one by one?
But anyways you can programmatically force to return back only one message at a time something like below:
static constraints = {
password validator: { String password, command ->
def errorMsgs = []
if (!password){
errorMsgs << 'password.invalid.blank' //'password.invalid.null'
return errorMsgs
} else if (!(password.size() in (8..64))){
if (someService.isPasswordSameAsUsername(password)){
errorMsgs << 'password.invalid.sameasuser'
}
errorMsgs << 'password.invalid.length'
return errorMsgs
} else if (/*password not matching YourRegex*/){
errorMsgs << 'password.invalid.specialCharacters'
return errorMsgs
} else if (someService.isPasswordSameAsUsername(password)){
errorMsgs << 'password.invalid.sameasuser'
return errorMsgs
}
}
}
I think we have to take care of the special cases where more than one message is sent back by adding control logic as done above for password length and its match with user name.
Take a look at grails validate, the interesting thing is that you can pass property names to validate(). The second thing is errors property that implements spring Errors interface. You can use it to clean up messages to show only one for property. Write a custom validator as dmahapatro suggested is a good approach.

CodeIgniter: Disallowed Key Characters

I have the same problem as the people below, but the solutions offered for them does not work for me.
CodeIgniter - disallowed key characters
CodeIgniter Disallowed Key Characters
Disallowed key characters error message in Codeigniter (v2)
I get "Disallowed Key Characters" when I submit a form.
I have CSRF protection enabled, and I am using arrays in my form field names (i.e., search[] as the name as there are multiple selection dropdown options). I have a feeling it is the "[]" in the form name that bothers this form.
I have followed all advice I could see in the posts above.
I disabled CSRF temporarily,
I disabled XSS temporarily,
I edited $config['permitted_uri_chars'] and
I edited Input.php where this message is generated.
Anybody has any additional ideas of what could cause this problem on form submission?
Thanks!
Like my answer here — you just need to update the regex in MY_Input->_clean_input_keys() to allow more characters (eg escaped JSON, or escaped HTML/XML)
Allow just 'English': !preg_match("/^[a-z0-9\:\;\.\,\?\!\#\#\$%\^\*\"\~\'+=\\\ &_\/\.\[\]-\}\{]+$/iu", $str)
Allow Chinese Characters: !preg_match("/^[a-z0-9\x{4e00}-\x{9fa5}\:\;\.\,\?\!\#\#\$%\^\*\"\~\'+=\\\ &_\/\.\[\]-\}\{]+$/iu", $str)
My full working function looks like this:
public function _clean_input_keys($str) {
// NOTE: \x{4e00}-\x{9fa5} = allow chinese characters
// NOTE: 'i' — case insensitive
// NOTE: 'u' — UTF-8 mode
if (!preg_match("/^[a-z0-9\x{4e00}-\x{9fa5}\:\;\.\,\?\!\#\#\$%\^\*\"\~\'+=\\\ &_\/\.\[\]-\}\{]+$/iu", $str)) {
/**
* Check for Development enviroment - Non-descriptive
* error so show me the string that caused the problem
*/
if (is_env_dev()) {
var_dump($str);
}
exit('Disallowed Key Characters.');
}
// Clean UTF-8 if supported
if (UTF8_ENABLED === TRUE) {
return $this->uni->clean_string($str);
}
return $str;
}
my_helper.php
if (!function_exists('is_env_dev')) {
function is_env_dev() {
return (
defined('ENVIRONMENT') && strtolower(ENVIRONMENT) == 'development' ||
defined('ENVIRONMENT') && strtolower(ENVIRONMENT) == 'testing'
);
}
}
Thanks, but I found a comment hidden way below (right at the bottom at the time of this writing) on another post here: CodeIgniter Disallowed Key Characters
The comment suggested that I add $str to the exit() comment to test. This indicated that I had a missing double quote in my form fields. It is a very complex form built up dynamically, with 300 lines of code, so easy to miss.
Hope this answer (and the comment that inspired it) helps someone else.
Validating the source of the output could prevent problems such as this one :-)
Regards

CodeIgniter: set_message for max_length[x]

How do you set an error message for max_length and min_length rules. For instance, if I set a rule max_length[6], I'd like the error message to display
Max characters allowed: 5
I got the same problem and even though this post is old, there's no correct answer.. You just have to use the string placeholder %s in second place of your message. In the documentation (http://codeigniter.com/user_guide/libraries/form_validation.html#settingerrors) there is an example for a field not being empty:
$this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
There, it uses the %s placeholder for the name of the field, but if you modify the 'max_length' message putting the field name first and the length second like this:
$this->form_validation->set_message('max_length', 'The field %s max length is %s');
it will work. Is not the best solution, but that one works for me. Hope it helps
application/language/en/en_lang.php I have this:
$lang['name'] = "Name";
$lang['form_required'] = "is required.";
application/language/es/es_lang.php I have this:
$lang['name'] = "Nombre";
$lang['form_required'] = "es requiero.";
application/controllers/yourController.php I have this:
$this->form_validation->set_rules('name', $this->lang->line('name'), 'required|alpha|xss_clean');
$this->form_validation->set_message('required', '%s ' . $this->lang->line('form_required'));
I hope this help!
#Daniel is correct. Per CodeIgniter's documentation, you can override the default error message for any validation rule (such as "min_length", "max_length", etc.) like this:
$this->form_validation->set_message('validation_rule', 'Your message here');
So, in your example you could do:
$this->form_validation->set_message('max_length', 'Max characters allowed: 5');
Simply include that where your validation rules exist.
gAMBOOKa,
create a 'new' rule that also checks for max_length
$this->form_validation->set_rules('username', 'Username', 'required|_max_length[12]');
and for the method..
function _max_length($val)
{
if (strlen($this->input->post('username')) > $val)
{
$this->form_validation->set_message('_max_length', 'Max characters allowed: 5')
return FALSE;
}
return TRUE;
}
add this to your controller as a new rule and set the message like so ---^
CodeIgniter has one of the better documentations out of all the frameworks. Read the userguide on their site or the one in your CI directory.
http://codeigniter.com/user_guide/libraries/form_validation.html#settingerrors
Take a look in system/language/english/form_validation_lang.php and you'll find
$lang['max_length'] = "The %s field can not exceed %s characters in length.";
Which is easily overridden by copying it to
application/language/english/form_validation_lang.php
And changing it to the string you'd like. Do not edit the file in system/ directly, then it'll be overwritten if you upgrade CodeIgniter.
There is no need to add a new method. You may set a custom message to a form validation error by accessing the "max_length" rule as shown below.
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]', array('required' => 'Username is required.','max_length' => 'Max characters allowed: 5')
);
Note: This is also applicable for "min_length" rule.

Ruby email check (RFC 2822)

Does anyone know what the regular expression in Ruby is to verify an email address is in proper RFC 2822 email format?
What I want to do is:
string.match(RFC_2822_REGEX)
where "RFC_2822_REGEX" is the regular expression to verify if my string is in valid RFC 2882 form.
You can use the mail gem to parse any string according to RFC2822 like so:
def valid_email( value )
begin
return false if value == ''
parsed = Mail::Address.new( value )
return parsed.address == value && parsed.local != parsed.address
rescue Mail::Field::ParseError
return false
end
end
This checks if the email is provided, i.e. returns false for an empty address and also checks that the address contains a domain.
http://theshed.hezmatt.org/email-address-validator
Does regex validation based on RFC2822 rules (it's a monster of a regex, too), it can also check that the domain is valid in DNS (has MX or A records), and do a test delivery to validate that the MX for the domain will accept a message for the address given. These last two checks are optional.
Try this:

Resources