Rails 3: validate REGEX fails if no value input - regex

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

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.

How to validate non required filed in Yup

How to validate a non required filed that should not contain the following special characters #<`> and a white space before dot(.) I have Regex \`|\#|\&|\<|\ \.|\> to validate above condition but don't have any idea how to this regex with the yup.matches(). Thanks in advance
Regex: \`|\#|\&|\<|\ \.|\>
my validation schema is:
const validationSchema = function (values) {
var regx = new RegExp(/\`|\#|\&|\<|\ \.|\>/gms);
return Yup.object().shape({
about: Yup.string()
.matches(expression, 'about should not contain ` # < > \n')
})
}
Assuming your regular expression works you could use the string.matches function. Here is the example from the documentation:
var v = string().matches(/(hi|bye)/);
v.isValid('hi')
.should.eventually()
.equal(true);
v.isValid('nope')
.should.eventually()
.equal(false);
See this today trying to solve same problem. I know i am late !
return yup.object().shape(
{
about: yup
.string()
.nullable()
.notRequired()
.when("about", {
// WARNING required itself => add cyclic dep at the end of the yup shape
is: (value: string) => value?.length,
then: (rule) => rule.matches(regx, "about should not contain ` # < > \n"),
}),
},
// Add Cyclic deps here because when require itself
[["about", "about"]]
);
Credit to this post : Yup validation for a non-required field
Please take a great care to the second parameter of the shape function. it will prevent cyclic check of the about on itself. (try it without, to see difference).

CodeMirror electricInput does not match expression with leading whitespace

In my custom mode for CodeMirror, I want the electricInput event to fire when the user types a line starting with the word bank (with optional leading whitespace).
I have electricInput set up like this: electricInput: /\s*bank$/i
The event DOES fire when the user types bank at the beginning of a line. It does NOT fire when there are spaces before the word bank. Why?
(the RegEx seems to be fine. I have a grammar rule in that mode with the same RegEx, and it matches the token as expected, regardless of leading white spaces:
CodeMirror.defineSimpleMode("myMode", {
start: [
{regex: /\s*bank$/i, token: 'bank', sol: true, indent: true}
Thanks to Marijn's kind help on the CodeMirror discussions forum, I was able to solve this: a custom indent function needs to be passed to defineSimpleMode. Then, we still need to set electricInput (because otherwise the indent function does not get called when typing bank). But no event handler for onElectricInput is required.
CodeMirror.defineSimpleMode("myMode", {
start: [
...
],
meta: {
electricInput: /\s*bank$/i,
indent: function (state, textAfter, line) {
if (textAfter.substring(0, 4).toLowerCase() === 'bank') return 0
return 2;
}
}
});

mongo shell search for value like "/"fubak#drooop.com"/"

I may have let a bug loose on our code that essentially ruined some of our db data.
Every now and again we come across a username that has " " in his email so we need to fix this.
How can I search for a value like "/"fubak#drooop.com"/" in one field using my mongo shell?
I have been trying all the combinations I can think of like:
db.users.find(username: /"/" .* /)
and
db.users.find(username: //.*//)
or
db.users.find(username: /"".*/)
But nothing seems to work.
new RegExp('^".*')
This finds all the records that start with ".
Thanks.
Try this:
db.users.find({ email: "(?:[^\\"]+|\\.)* })
This will match all documents which contains quotes in the email
Not to sure which one is you problem, so the solutions to both possible scenarios with data in MongoDB like this:
{ "email" : "\"/\"fubak#drooop.com\"/\"" }
{ "email" : "/fubak#drooop.com/" }
{ "email": "\"blablabla#blip.ca\"" }
First document match:
db.problem.find({ email: /^\"/ })
Second document match:
db.problem.find({ email: /^\// })
Third document match
db.problem.find({ email: /^\"/ })
Do not know what you mean otherwise by "having quotes" as that is not valid JSON and by extension is also invalid BSON.

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.