How to validate non required filed in Yup - regex

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).

Related

One-liner to extract domain from email address

How to optionally extract domain from local-part#domain? My attempt is
Try(email.split("#")(1)).toOption
but seems there should be a way without depending on exception handling. Ideally, I am after one-liner.
Not one liner, and only works on 2.13. But this seems very clear to me.
def extractDomain(email: String): Option[String] = email match {
case s"${_}#${domain}" => Some(domain)
case _ => None
}
(Note, if there are more than one # sign, this will just split on the first one).
email.dropWhile(_ != '#').drop(1)
email.split("#").lastOption
These are equivalent ONLY if what's passed is an email address.
If the string passed doesn't include # then lastOption will still return a Some() of the entire string, whereas your solution will return a None.
So if you can trust your input then this answer provides a cleaner approach.
You can use Some(email.split("#")(1)), this will split the String and then wrap in Some, which is instance of Option.
Let me cheat a little: I will prepare separate file Email.scala with extractor:
object Email{
def unapply(mail: String): Option[(String, String)] = {
mail match {
case s"$user#$domain" => Some(user, domain)
case _ => None
}
}
}
and then it can be used with pattern matching:
val Email(_, domain) = "test#domain.com"
Not a one-liner, but I always match on array extractors when I do String.split (pre-2.13), I think it's short enough and reads much better than getting parts by index.
email.split("#", 2) match {
case Array(_, domainPart # _*) => domainPart.headOption
}
limit = 2 makes sure that domainPart has at most 1 element.
Note you don't need a catch-all in this case, since split will always return at least one value in the array (although makes sense to cover it with tests to protect against future changes).

Custom vallidator to ban a specific wordlist

I need a custom validator to ban a specific list of banned words from a textarea field.
I need exactly this type of implementation, I know that it's not logically correct to let the user type part of a query but it's exactly what I need.
I tried with a regExp but it has a strange behaviour.
My RegExp
/(drop|update|truncate|delete|;|alter|insert)+./gi
my Validator
export function forbiddenWordsValidator(sqlRe: RegExp): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
const forbidden = sqlRe.test(control.value);
return forbidden ? { forbiddenSql: { value: control.value } } : null;
};
}
my formControl:
whereCondition: new FormControl("", [
Validators.required,
forbiddenWordsValidator(this.BAN_SQL_KEYWORDS)...
It works only in certain cases and I don't understand why does the same string works one time and doesn't work if i delete a char and rewrite it or sometimes if i type a whitespace the validator returns ok.
There are several issues here:
The global g modifier leads to unexpected alternated results when used in RegExp#test and similar methods that move the regex index after a valid match, it must be removed
. at the end requires any 1 char other than line break char, hence it must be removed.
Use
/drop|update|truncate|delete|;|alter|insert/i
Or, to match the words as whole words use
/\b(?:drop|update|truncate|delete|alter|insert)\b|;/i
This way, insert in insertion and drop in dropout won't get "caught" (=matched).
See the regex demo.
it's not a great idea to give such power to the user

Using Regular Expression in Mvc 4 Razor View's cshttml page for jquery email validation

My Jquery Regular expression for email validation throwing syntax error.
Error : "Unexpected character \". Below is my code. please anyone give me right solution.
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
return true;
}
else {
return false;
}
}​
You have to escape the # sign with two ## alike so :
var filter = /^([\w-\.]+)##((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
try
var filter = /^([-\w\.]+)#...
note the - upfront instead of \w-\.
- in between means range as in [a-z] here with `\w' it does not make sense.
btw whats with \[ and \] after #
Try this:
(?:.*)#(?:.*).(?:.*)

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

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.