Zend Regex Route help - regex

I am trying to create a Zend_Controller_Router_Route_Regex route to process URLs in the following form:
search?q=chicken/page=2 where the first regex subpattern would be chicken and second one would be 2. As for the second part where page=2, I want to make it optional if it is the first page, that is page=1. So another url such as search?q=chicken would also be valid and is equivalent to search?q=chicken/page=1.
Here is my attempt albeit without any success, but to give you a better picture of what I am trying to do.
$route = new Zend_Controller_Router_Route_Regex(
'search\?q=([a-zA-Z0-9]+)(?:/page=(\d+))',
array(
'page'=> '1',
'module' => 'default',
'controller' => 'search',
'action' => 'index' ),
array( 1 => 'query', 2 => 'page' ),
'search?=%s/page=%d');
$router->addRoute('search', $route);
The problem here is I cant compose the correct regex.
Thanks in advance.
EDIT #1
The correct regex, as pointed out by MA4, is 'search\?q=([a-zA-Z0-9]+)(?:/page=(\d+))?'
The real problem is pointed by Darryl. Here is a little bit more info to put things into perspective.
My search text box and button
<form action="/search" method="get">
<input type="text" name="q" />
<input type="submit" value="Search" />
</form>
Every time I press the search button, I get the search?q=[text] request. How do I force it to go through the regex match route?
Here is what i want to do, however the code does not work
if($this->getRequest()->getParam('query')){
// redirect success
} else {
$url = "search?q=" . $this->_getParam('q');
$this->_redirect(route('search'), array('code' => 301 ));
}

/search?q=chicken/page=2 is not parsable by Zend Frameworks' router. The router will only see /search.
The router relies on the Path Info provided by the server and anything after the ? is the query string.
You would need to use a path such as this:
/search/[word] (default page 1)
/search/[word]/[page]
In which case your regex would become much simpler.

make the second part optionnal by adding a ? after it:
search\?q=([a-zA-Z0-9]+)(?:/page=(\d+))?

Related

Angular2 - Why does my reactive form input with an html pattern attribute is not validating correctly?

I'm struggling with a problem that I can't understand:
I need to validate an input field with a pattern="[0-9]+([,.][0-9])?" attribute on an angular reactive form with Validators.pattern, but it seems my ? quantifier at the end is not working...
What I want
I want to validate numbers with zero or one decimal maximum. As you can see on https://regex101.com/r/2D2sww/1, the regex is working great.
The actual problem
In my app I can enter as many decimals as I want without the Validator.pattern to do anything. Any other character invalidate the form, so my Validator is working.
Here is my code (simplified):
component.html
<form [formGroup]="myForm">
<input type="number" formControlName="myInputField" id="myInputField" pattern="[0-9]+([,.][0-9])?" required />
</form>
component.ts (Every import and declarations are skipped for clarity)
ngOnInit() {
this.myForm = this.formBuilder.group({
myInputField: [
"",
[Validators.required, Validators.pattern],
]
});
}
I already tried to use Validators.pattern(/^[0-9]+([,.][0-9])?$/) and Validators.pattern("[0-9]+([,.][0-9])?") as pointed in the documentation, but it doesn't change anything, so I suspect my Regex to be incorrect...
Any ideas ? Thanks, have a nice day :)
I think there is nothing wrong with your validator pattern regex,
you can remove the pattern's attribute from the input, it is redundant because you are initiating it from inside the ts file: 'myInputField': new FormControl(null, [Validators.pattern('^[0-9]+([,.][0-9])?$')]).
StackBlitz

How can I do both email control and custom domain control with regex?

I want to check text which entered form field. Text must be valid email and shouldn't contain specific domain between "#" and "." sign. How can I do this with using regex? For example I want an email that shouldn't contain "test" domain
mail#mail => Invalid
mail#test.com => Invalid (Because contain 'test' domain)
mail#mail.com => Valid
HTML
<form>
<input type="text" id="email">
<button type="submit" id="sendMail">Send</button>
</form>
I can handle valid email with following pattern:
JS
const btn = document.getElementById('sendMail');
btn.addEventListener('click', (e) => {
e.preventDefault();
const emailPtrn = /^(([^<>()\[\]\\.,;:\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,}))$/;
const email = document.getElementById('email');
alert(emailPtrn.test(email.value));
});
JSfiddle Link
How can I check this with single pattern?
Just add (?!test\.) negative look ahead after # in your current regex,
^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#(?!test\.)((\[[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,}))$
^^^^^^^^^^ This will reject any email if what follows immediately after # is test.
Regex Demo

AMAZON: Add to remote cart without leaving site

Hey I'm trying to set up a remote cart. Very frustrating though since Amazon doesn't list any code examples for a remote cart without the customer leaving the site.
Here's where I'm at so far. I can get someone to leave my site and add the product from my site to Amazon using this (From: http://docs.aws.amazon.com/AWSECommerceService/latest/DG/AddToCartForm.html):
<form method="GET" action="http://www.amazon.com/gp/aws/cart/add.html">
<input type="hidden" name="AWSAccessKeyId" value="Access Key ID" /> <br/>
<input type="hidden" name="AssociateTag" value="Associate Tag" /><br/>
<p>One Product<br/>
ASIN:<input type="text" name="ASIN.1"/><br/>
Quantity:<input type="text" name="Quantity.1"/><br/>
<p>Another Product<br/>
ASIN:<input type="text" name="ASIN.2"/><br/>
Quantity:<input type="text" name="Quantity.2"/><br/>
</p>
<input type="submit" name="add" value="add" />
</form>
But I want to make it so they can add an item to cart and stay on my site. It seems like this is how I accomplish that:
http://webservices.amazon.com/onca/xml?
Service=AWSECommerceService&
AWSAccessKeyId=[AWS Access Key ID]&
AssociateTag=[Associate Tag]&
Operation=CartCreate&
Item.1.OfferListingId=B000062TU1&
Item.1.Quantity=2
&Timestamp=[YYYY-MM-DDThh:mm:ssZ]
&Signature=[Request Signature]
But when I'm totally confused as to how to generate a timestamp and signature. Do I put this into a form action? Is there anywhere with code examples? I've been searching all day and can't find it. Any help greatly appreciated.
I'm using this method to generate api request url, and its totally working fine. Believe this will help you
$uri = "/onca/xml";
$asin = "B00C5AHTC0";
$end_point = "webservices.amazon.com";
$params = array(
"Service" => "AWSECommerceService",
"Operation" => "CartCreate",
'Version' => "2013-08-01",
"AWSAccessKeyId" => AWS_ACCESS_KEY,
"AssociateTag" => AWS_ASSOCIATE_TAG,
"Item.1.ASIN" => $asin,
"Item.1.Quantity" => "5",
"Timestamp"=> gmdate('Y-m-d\TH:i:s\Z')
);
// Sort the parameters by key
ksort($params);
$pairs = array();
foreach ($params as $key => $value) {
array_push($pairs, rawurlencode($key) . "=" . rawurlencode($value));
}
// Generate the canonical query
$canonical_query_string = join("&", $pairs);
$string_to_sign = "GET\n" . $end_point. "\n" . $uri . "\n" . $canonical_query_string;
$signature = base64_encode(hash_hmac("sha256", $string_to_sign, AWS_SECRET_KEY, true));
$request_url = 'http://' . $end_point. $uri . '?' .$canonical_query_string . '&Signature='.rawurlencode($signature);

change default form email type regex in symfony2

Using Symfony 2.3.4.
When I create a form with a field in it that's supposed to process emails I go and use the default email type:
builder->add('email', 'email', array(
'label' => 'Email',))
with only this, it successfully validates user inputs, only not the way I want, meaning:
how it works:
me --> notallowed
me#gmail --> allowed
how I need it to work:
me --> notallowed
me#gmail --> notallowed
me#gmail.com --> allowed
summing up:
I figured what I need is to change/customize the default regex that validates this which I guess is deep in one of the many files in symfony.
appreciate any tips regarding this, thanks
Actually, the validation that you are seeing here is the browser based HTML5 validation. The message that pops up if me is entered comes right from your browser, no Symfony involved. I find HTML5 validation unreliable for the most part. Best practice is to validate on the server side, and use some type of javascript validation for the client side.
for more info on setting up server side validation, see the symfony docs, they give some great examples and it is very useful.
You can handle email validation by javascript . Call any method on form submit like
function validate(){
var email=$('#email').val();
if(email!=""){
var re =/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!re.test(email)) {
alert('please Enter Valid email address');
}
}
<form onSubmit="return validate();">
<input type="text" name="email" id="email" placeholder="Please Enter your Email address" />
</form>
Please refer this following link for form field type email
Symfony form type email
If you want jquery validation for email
$('#formId').validate({
errorClass: 'help-block',
rules: {
'textFieldName': {
required: true,
email: true
}
},
messages: {
'textFieldName': {
email: "Invalid Email Address"
}
},
highlight: function (element) {
$(element).parent().parent().removeClass("success").addClass("error");
},
unhighlight: function (element) {
$(element).parent().parent().removeClass("error").addClass("success");
}
}); // validate

Jade Templates - Dynamic Attributes

I want to create attributes on the fly for some html elements.
In my case I'd like to set (or not) a disabled attribute according to user.role.
So, if user has permission to edit some field, I do not want to put disabled attribute on the element. Otherwise, I do want it.
I know that I can do this with these approaches:
- Approach 1 - Use Conditionals
if (user.role === 1)
input(type='text', name='foo')
else
input(type='text', name='foo', disabled)
- Approach 2 - Plain HTML
- var disabledAttr = (user.role === 1) ? "disabled" : "";
| <input type="text" name="foo" #{ disabledAttr} />
Approach 1 is bad because I need to repeat some code. With Approach 2 I do not need to repeat code but I have to use plain HTML instead of Jade markup.
I tried something like this:
input(type='text', name='foo', #{ disabledAttr} )
But jade generates the following code:
<input type="text" name="foo" disabledattr="" />
Any better idea?
Jade is quite clever when it needs to figure out how to render attributes. You can render your disabled attribute using this single line of jade markup
input(type='text', name='foo', disabled=role!==1)
You can to use a bunch of attributes in a conditional way:
input(type='text')&attributes(user.role === 1 ? {'disabled': 'true'} : {'class': 'admin', 'ng-model': 'vm.model.name', 'ng-click': 'vm.click()'})
This syntax works for me:
input(placeholder!="<%= translate('Add new item') %>")
where translate is a function that returns translated text.