I have a regex expression as follows:
return ( ! preg_match("/^([-a-z_ -])+$/i", $str)) ? FALSE : TRUE;
I need to add to it to allow a period, so that the input could be something like this:
"st. austell" or "st. thomas"
I have tried various ways to add the period to the above rule, but the page either crashes out and just displays a blank page, or my validation errors are triggered.
I have tried things like this, but to no avail.
([-a-z_ -.])
([-a-z_ -\.])
([-a-z_ -])\.
(\.[-a-z_ -]) etc etc...
I have tried everything and don't seem to bee having any luck - any ideas
Many Thanks
James
Three points:
The initial regex is redundant, since it specifies - twice.
[a-z_ .-] should work, you just have to let a-z together and - just after [ or just before ] (otherwise, - will be considered as a metachar).
return !condition ? false : true; should be simplified to return condition;, since condition already returns true or false (same logic for if(!condition) {var = false;} else {var = true;} which should be simplified to var = condition;).
Related
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).
I have two URL's addresses which I have filter for everyone of them:
all(uri: '/api/first/**')
{
before =
}
all(uri: '/api/second/**')
{
before =
}
I want to write just one filter for both.
So I have tried to write a filter with regex:
all(uri: '\\/api\\/(first|second)\\/.*', regex: true)
{
before =
}
But it doesn't work.
I have tried many ways ('**' / '.*' / invert: true)
But didn't succeed.
Does someone know where the mistake and what the right way to write the filter?
Thanks...
As per the documentation, uri is an ant path and does not support regular expressions. You need to rely on find:
all(regex: true, find: '/api/(first|second)/.*')
{
before = {
...
}
}
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:
(?:.*)#(?:.*).(?:.*)
I'm using http://bassistance.de/jquery-plugins/jquery-plugin-validation/ to validate my form. Unfortunately, there is no text only method. So I tried to write my own:
$(document).ready(function(){
$("#staffedit").validate(
{
rules: {
editDisplayName: {
textonly: true,
required: true
}
}}
);
jQuery.validator.addMethod(
"textonly",
function(value, element)
{console.log('textonly called.');
console.log(/[-.\w\s]/.test(value));
return this.optional(element) || /[-.\w\s]/.test(value);
},
jQuery.format("Please only enter letters, spaces, periods, or hyphens.")
);
});
The method gets called, since my console.log function does output to the console at the appropriate times. What I don't understand, is why I can still put $ or * in the input field. I can put anything in there, and it still gets evaluated as valid.
I used http://regexpal.com/ to test the regex, and it works fine there.
So, how do I get the plugin to only allow text, spaces, periods, and hyphens?
On a side note, I'd also like to allow characters with accents, like à, É, ā, or ô...
The problem was with how the test() function works. It returns true if it makes any match. That's what had me so confused. The regex's I was using were actually doing what I thought they should. See http://www.w3schools.com/jsref/jsref_regexp_test.asp
/[^-\.a-zA-Z\s]/.test("David"); //Returns false
/[^-\.a-zA-Z\s]/.test("Davi$ *d"); //Returns true
//without the ^
/[-\.a-zA-Z\s]/.test("Davi$ *d"); //Returns true
/[-\.a-zA-Z\s]/.test("David"); //Returns true
As you can see, that's not very helpful. So what I did was pull the test out of the return statement. Like this:
$(document).ready(function(){
$("#staffedit").validate(
{
rules: {
editDisplayName: {
textonly: true,
required: true
}
}}
);
jQuery.validator.addMethod(
"textonly",
function(value, element)
{
valid = false;
check = /[^-\.a-zA-Z\s\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02AE]/.test(value);
if(check==false)
valid = true;
return this.optional(element) || valid;
},
jQuery.format("Please only enter letters, spaces, periods, or hyphens.")
);
});
So I check to see if any of the characters I don't want exist, if they don't test() returns false, so it's valid.
I also figured out the unicode stuff. [\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02AE] matches a bunch of stuff, I used http://en.wikipedia.org/wiki/List_of_Unicode_characters to figure out what to put in. I think I got everything I wanted. Thanks to Kyle Schmidt for posting the link to Javascript + Unicode regexes that helped me figure out the \u syntax. I should probably check the unicode a bit more thoroughly, but that should be enough for now.
Problem solved.
If you get the additional methods js there's a letters validator in there
http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/additional-methods.js
You want letterswithbasicpunc I believe
Putting the ^ inside a character class will negate what's in the character class. I'd go for [-.\w\s]
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.