How do i write a regular expression which accepts only value "1" in the textbox
and it should not accept zero or greter than "1"
if (theTextBoxValue == "1") {
// accept
} else {
// reject
}
You don't need regex for this simple task. And, if you only accept "1" in a user input, why provide such an input to the user at all?
/^1$/
… but for a "Must be this value, exactly this value, and nothing but this value" test, you would be much better off with a simple string comparison.
/^1$/ but a simple == "1" will be enough in most languages (or .equals("1")).
I saw your previous question (using the jquery validationEngine), and I was intrigued by it so I started looking.
The problem with using a funcCall (as you were trying in the old post) is that the function is called without any context (has no arguments, and has this == window), so you can't tell which input field is being validated.(I solved this with a trick - see example & comments linked below).
Another solution I found was using regex(as you are trying now).
This is the entry you have to add to the languages file:
"isOne":{
"regex":"/^1$/",
"alertText":"* Only '1' is valid [regex]"
}
This is how you use it on the input field:
<input type="text" class="validate[custom[isOne]]">
And this is how you start the validation engine:
$('#form').validationEngine({
validationEventTriggers:"change"
});
You can view a working example using both function and regex here
Don't think you want to use regex for this.
Pattern: ^1$
Related
I´m writing automation test for Api Rest.
In the body response to return:
"New Current Account"
I do the follow validation:
Assert.AreEqual("New Current Account", response.Content);
But it doesn´t work the Nunit return failed beacuse:
Message:
Expected string length 19 but was 21. Strings differ at index 0.
Expected: "New Current Account"
But was: ""New Current Account""
-----------^
Can someone help me?
Apparently, the string being returned actually contains quotes.
The proper way to reference this is by escaping the quotes that are part of the data in the string you use for an expected value.
Assert.AreEqual("\"New Current Account\"", response.Content);
This is preferable to using logic to trim off the quotes, because you are comparing actual to expected data without modifying either.
I resolved with follow alternative.
Assert.AreEqual("New Current Account", response.Content.Trim('"'));
I'm developing a web application using Angular 6. I have a question:
I'm creating a custom input component (for text input) such as:
#Component({
selector: 'input-text',
templateUrl: './input-text.component.html'
]
})
export class InputTextComponent {
#Input() pattern?: string;
}
I would like a user can insert a regular expression for the validation of the input field, in this way:
<input-text pattern="^[a-z0-9_-]{8,15}$"></input-text>
The template of my component is defined like this:
<input type="text" [attr.pattern]="pattern"/>
Unfortunately I know absolutely nothing about regular expressions.
I would like to do two things:
1 - Create a method that checks the validity of the regular expression and changes the visual style.
2 - Make sure that if the input (with a pattern field) is inserted into a form, the attribute form.valid remains false until the expression is valid.
Thanks for your help!
Check regex validity
You can simply catch exceptions thrown by the RegExp constructor when instanciating it.
try {
const regex = new RegExp(pattern);
} catch (error) {
// If it goes here, then the regex model is not correct
console.error(error.message)
}
Change the visual style
You can simply use the ngClass attribute to change your input style.
If you enter the catch statement, set a style variable to change the class like so
private hasBadInput: boolean;
// [...]
catch (error) {
hasBadInput= true;
}
Then apply a specific class in that case:
<input-text [ngClass]="{'yourErrorClass': hasBadInput}"><input-text>
Form validity
You did well using [attr.pattern], the form should automatically consider the entered pattern. You should try your form with a hard written regex before, and then use the input one.
Follow this official guideline to create Angular 2+ forms.
I am using REST-API for testing
I am stuck where I am checking the response with some specific string.
please refer below info
I got the response from a request is
{
"clusters":[
{
"id":10,
"name":"HP2",
"status":2,
"statusDisplay":"HParihar#4info.com",
"lastModifiedBy":"HParihar#4info.com",
"lastModifiedTime":"06/08/2017 23:42",
"sitesAppsCount":0
},
{
"id":799,
"name":"Regression_cluster_111_09",
"status":2,
"statusDisplay":"admin#4info.net",
"lastModifiedBy":"admin#4info.net",
"lastModifiedTime":"07/11/2017 08:19",
"sitesAppsCount":0
}
]}
and I wanted to match just
"name":"Regression_cluster_111_09",
"status":2,
"statusDisplay":"admin#4info.net",
"sitesAppsCount":0
right side values I'll be keeping as hard coded.
any guesses?
Since you are only checking those 4 parameters are in response or not.
Do no use regex for this.
Use jsonObject's find key/value feature.
Check whether the values to the keys are there.
If key/value is null, the parameter is not in response.
I got my answer
I used the following regex
"name":"Regression_cluster_111_09","status":2,"statusDisplay":"admin#4info.net","lastModifiedBy":"[a-z]+#[0-9a-z]+\.[a-z]+","lastModifiedTime":"[0-9]{2}\/[0-9]{2}\/[0-9]{4}\ [0-9]{2}:[0-9]{2}","sitesAppsCount":0
or I can simply use
"name":"Regression_cluster_111_09","status":2,"statusDisplay":"admin#4info.net",.+"sitesAppsCount":0
thank you all
I need to send a custom email message to every User of a list ( List < User > ) I have. (I'm using C# .NET)
What I would need to do is to replace all the expressions (that start with "[?&=" have "variableName" in the middle and then ends with "]") with the actual User property value.
So for example if I have a text like this:
"Hello, [?&=Name]. A gift will be sent to [?&=Address], [?&=Zipcode], [?&=Country].
If [?&=Email] is not your email address, please contact us."
I would like to get this for the user:
"Hello, Mary. A gift will be sent to Boulevard Spain 918, 11300, Uruguay.
If marytech#gmail.com is not your email address, please contact us."
Is there a practical and clean way to do this with Regex?
This is a good place to apply regex.
The regular expression you want looks like this /\[\?&=(\w*)\]/ example
You will need to do a replace on the input string using a method that allows you to use a custom function for replacement values. Then inside that function use the first capture value as the Key so to say and pull the correct corresponding value.
Since you did not specify what language you are using I will be nice and give you an example in C# and JS that I made for my own projects just recently.
Pseudo-Code
Loop through matches
Key is in first capture group
Check if replacements dict/obj/db/... has value for the Key
if Yes, return Value
else return ""
C#
email = Regex.Replace(email, #"\[\?&=(\w*)\]",
match => //match contains a Key & Replacements dict has value for that key
match?.Groups[1].Value != null
&& replacements.ContainsKey(match.Groups[1].Value)
? replacements[match.Groups[1].Value]
: "");
JS
var content = text.replace(/\[\?&=(\w*)\]/g,
function (match, p1) {
return replacements[p1] || "";
});
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.