How can I create a validator that allows only letters as dashes as input?
Thanks in advance
EDIT
This is what I have so far..
If I write test it passes and if I write 123 it fails but if I write test123 it passes which I don't want
EDIT
The validator now works as I wanted. :)
override protected function doValidation(value:Object):Array
{
results = [];
var regEx:RegExp = /^[a-zA-Z _-]*[a-zA-Z][a-zA-Z _-]*$/;
if(regEx.test(value as String)) {
trace("passed")
return results;
} else {
var err:ValidationResult = new ValidationResult(true,"","","Only letters are allowed");
results.push(err);
trace("error")
}
return results;
}
OK the correct RE is ^[a-zA-Z _-]*[a-zA-Z][a-zA-Z _-]*$
Related
I need to replace all occurencies of $connection with $link?
I know I could do with a regexp replacement using my IDE, but I need to be able to re-run the sostitution automatically.
So I want to use rector.
Is there a way to replace a var name ? Which is the rule name?
There are a couple of potentially suitable rules & sets:
RenamePropertyRector
There is also the '\Rector\Set\ValueObject\SetList::NAMING' set that can be enabled in rector.php that will perform some similar rules, like renaming variables according to the type.
The complete set of basic rules (not including framework or library-specific) are at https://github.com/rectorphp/rector/blob/main/docs/rector_rules_overview.md
I create a custom rule, very specific for my needs
<?php
namespace Rules;
use PhpParser\Node;
use Rector\Core\Rector\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
use PhpParser\Node\Expr\Variable;
class ReplaceConnectionVarNameWithLink extends AbstractRector
{
public function getNodeTypes(): array
{
return [
Variable::class
];
}
public function getRuleDefinition(): \Symplify\RuleDocGenerator\ValueObject\RuleDefinition
{
return new RuleDefinition(
'rename $connect into $link',
[]
);
}
public function refactor(\PhpParser\Node $node)
{
if (!$this->isName( $node, 'connection')) {
// return null to skip it
return null;
}
$node->name = "link";
return $node;
}
}
Suppose I have a recipe called Garlic parmesan butter. I need to return an object when the appropriate name has been found.
Now in a simple ad-hoc solution I can search in the following way:
class SearchRecipe {
late RecipeModel recipe;
RecipeModel returnRecipe(String? suggestion) {
for (int i = 0; i < Store.instance.getAllRecipes().length; i++) {
if (suggestion == Store.instance.getAllRecipes()[i].recipeName) {
return Store.instance.getAllRecipes()[i];
}
}
return recipe;
}
}
But I need a simple way where if the user types in Garlic butter I need to return the object associated with the Garlic Paremesan butter.
How can I do it?
Edit: I should've clarified that I'm working with a List of objects. So the Store.instance.getAllRecipes() basically returns a List<RecipeModel>.
Update 1: This is what I've written:
class SearchRecipe {
//late RecipeModel recipe;
RecipeModel returnRecipe(String? suggestion) {
List<RecipeModel> results = [];
suggestion!.split(' ').forEach((s) {
results.addAll(Store.instance
.getAllRecipes()
.where((element) => element.recipeName!.contains(s)));
});
results = results.toSet().toList();
for (int i = 0; i < results.length; i++) {
return results[i];
}
return results[0];
}
}
String search = 'Garlic butter';
List<String> list = [
'Garlic Paremesan butter',
'Butter',
'Garlic',
'Butter Garlic',
'Paremesan',
'Stackoverflow'
];
List<String> results = [];
search.split(' ').forEach((s) {
results.addAll(list.where((element) => element.contains(s)));
});
// Avoid repeated values
results = results.toSet().toList();
Split the user input at spaces. Then you have a list. You can check the list and depending on your preference implement a variety of behaviors.
You can match if all words in the list are found. You can return if at least one of the words is matched.
You could give preference to more contained words or you could check the order of words.
In either case you would also not check for equality but use a function like includes / contains to check whether the searched word is part of the name.
(Checking the order could be done by remembering which words you already identified and only searching after the words that were found. In your example you would find ‘garlic’ and after that you would just look through ‘paremesan Butter’ and try to find ‘butter’)
first split the input text
var string = "Hello world!";
string.split(" ");
// ['Hello', 'world!'];
then iterate over each word in above array and check whether the above
Store.instance.getAllRecipes()[i].recipeName contains above word.
if(str.equalsIgnoreCase(str))
{
//remaining code
}
try contains method.
.contains()
This is my search code please see then solution, thank you.
You have to use like this
$report_ex = Expenses::where(condition)->where(condition)->get();
or
$report_ex = Expenses::where(condition)->where(condition)->first();
If you are using
$report_ex = Expenses::where(condition)->where(condition)->first();
then you need to call
if(!empty($report_ex))
{
// your code
}
else
{
//your code
}
But if you are using
$report_ex = Expenses::where(condition)->where(condition)->get();
then you should use
if(count($report_ex) > 0)
{
// your code
}
else
{
// your code
}
since get function returns an empty object
I have made code with is work great for me, but I want to make email validation to require # on the field. Here is the code
if (!$('#contact_email').val()) {
if ($("#contact_email").parent().next(".validation").length == 0) // only add if not added
{
$("#contact_email").parent().after("<div class='validation' style='color:red;margin-bottom: 20px;'>Ange e-postadress</div>");
}
e.preventDefault(); // prevent form from POST to server
$('#contact_email').focus();
focusSet = true;
} else {
$("#contact_email").parent().next(".validation").remove(); // remove it
}
And the input is
<input type="text" class="form-control" placeholder="E-post" name="Email" id="contact_email" onblur="validate()">
I dont use basic email field because I don't want to be on english.
How can i implement # to be required on this text input. Thank you
Hey Use This function:
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\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,}))$/;
return re.test(email);
}
found here:
Validate email address in JavaScript?
Try this for email validation:
function isEmail(email) {
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (email.match(mailformat)) {
return true;
} else {
return false;
}
}
Checking as follows:
if (email != "") {
if (!isEmail(email)) {
alert("invalid");
}
}
You can use regular expression to check for an "#" and a "." field.
Regex:
var regex= /\S+#\S+\.\S+/;
return regex.test(email);
The above code will return true if the regular expression is matched. This expression checks for an # and a . to be present in the given string.
Heres the documentation on .test http://www.w3schools.com/jsref/jsref_regexp_test.asp
I've noticed other answers have better regular expressions as the above will allow for multiple #'s and .'s to be present.
With the new validator object - is it possible to replace the validation error inside the validation rule triggered? to not only return the static error message but maybe some dynamically genereted one?
public function validateLength($data) {
...
$length = mb_strlen($data['name']);
$this->validator()->getField('name')->setRule('validateLength', array('message' => $length . 'chars'));
...
}
does not work, of course (too late I guess)
I want to actually return the lenght of the string (you used 111 chars from 100 allowed) for example - but for this I would need to be able to replace the message from inside the (custom) validation method
$this->validate['name']['validateLength']['message'] = $length . 'chars';
also never worked so far. it would always return the previous (static) error message from the $validate array
public function customValidator($data) {
....
if ($validates) {
return true;
} else {
return 'my new error message';
}
}
The following snippet should do the trick:
public function validateLength($data) {
...
$length = mb_strlen($data['name']);
$this->validator()->getField('name')->getRule('validateLength')->message = $length . 'chars';
...
}