Alpaca JS doesn't take into consideration if the regex pattern contains length limit - javascript

I am building a web application, using alpaca.js. I notice a problem when using regex patterns. If the pattern contains length it is not taken into consideration. For example this pattern "[0-9]{5}" should permit only 5 numbers, but it validates the numbers and not the length. To fix this I added min and max length, but it is a big problem if i have this kind of pattern ^[0-9]{1,3}([a-zA-Z]?)$.
Did somebody faced this issue before? Thanks

What you do is correct but, this will be used for schema validation and in your example you maybe need a mask rather than a regex. The mask will allows a user to more easily enter fixed width input where you would like them to enter the data in a certain format (dates,phone numbers, etc)
"options": {
"fields": {
"cap": {
"maskString": "99999" // 9 is a number, and here the mask will supports 5 digits
}
}
}
To use the maskString option you need first to import/add the Masked Input Plugin (the website is down, you could grab it from CDNJS or github)
For more details on maskString see Example 4 in Alpaca text field documentation.
For more details on Masked Input Plugin see this github repository.
And here's a fiddle for your example.
Hope this helps you.

Related

Lat/Long mask positive/negative detection

Hey all I am trying to create a mask for my 2 input boxes that will house the latitude and longitude.
Taken that the latitude can be a positive or negative number and the same goes for longitude. The issue being is that I am trying to come up with a regex that can give the user the ability to first chose if its going to be a positive or negative number then give user the mask of (-/+)XXX.XXXXXX.
However, I am not getting too close to the conclusion and so I am asking for a some help in reaching that goal.
I have set up a JSFiddle of what I have so far, which is not much, in order to archive my goal.
$('.mask').inputmask({
regex: String.raw `^[-/*][0-9]{3}[.][0-9]{7}$`
});
The above code works for negative numbers but when typing out, say 100., it just sits there because its waiting on the - in order to begin. I thought adding the * it would allow it to input a positive number. The above should allow the user to input in the format of -XXX.XXXXXX OR XXX.XXXXXXX.
I still need to figure out how to also tell when the first part (xxx.) is only 1 or 2 digits instead of 3 which makes the user have to put in a 0's in front of said number digits.
So valid input would be like so:
-2.984593 instead of -002.984593
-74.192822 instead of -074.192822
-102.738631
7.653721 instead of +007.653721
10.746633 instead of +010.746633
110.938365
How can this be formatted in order to work as I need it to?
You could simply make the dash optional:
^-?\d{3}\.\d{7}$
I took the liberty of refactoring your RegEx pattern ([0-9] -> \d, [.] -> \.).
As for allowing the first part to be one or two digits, you could use:
^-?\d{1,3}\.\d{7}$

Angular Input mask for Binary numbers

I am trying to build an input component which accepts only BINARY numbers from user. With a separator.
For example:
As user types, component should only accept 0/1 and append mask - after each binary digit.
I tried PrimeNG p-inputMask which does not accept regular expressions.
Also tried NgxMaskModule. But still no luck.
Are here any other plugins which would help?
Or Could I write a function by myself?
You can write your own function that will be filter your input values, ngx-mask does not have standard mask for Binary numbers. Probably you can write your custom pattern for mask, but it`s much more easy to write a function
Check this with NGX
https://www.npmjs.com/package/ngx-mask#patterns--character-string--pattern-regexp-optional-boolean
You can add your own patterns.
Usage:
<input type='text' [patterns]="customPatterns" mask="0-0-0-0" >
and in your component
public customPatterns = {'0': { pattern: new RegExp('\[0-1\]')}};
(for 1 and 0 only)
Check this cool tool for regex:
https://www.regextester.com/95029

formating UK mobile to international number with Zapier Code Javascript function

The scenario is...
A visitor comes to my landing page and completed the form, which included a telephone number.
Using Zapier I then pass that form data to ActiveCampaign.com using a "ZAP".
However as ActiveCampaign is in USA, they require the phone number formatting to international standard, instead of local UK.
Most numbers in UK are 07788990022
But it needs to be presented as +447788990022
So I need to use this built in function of Zapier listed below
https://zapier.com/help/code/
And need some Javascript code writing that will check the number
Is it valid UK mobile number? I.e. 11 digits
Remove all spaces, and trim
If 2nd character is a 7 then replace 1st character (which should be a 0) with +44
I really dont have any idea how to do this! I was hoping for a built in function on Zapier, but apparently not. Any ideas would be awesome!!!
David here, from the Zapier Platform team.
This seems like a pretty straightforward js question! This will be pretty "dumb" validation, but will work assuming the input is correct.
You'll have a code (javascript) step and set the input to be phone: input from step 1. Your code will look like this:
var ph = inputData.phone.replace(/\s+/g, '') // remove all whitespace from string
if (ph.length !== 11) {
// invalid phone number. do nothing?
return []
}
if (ph[1] === '7') {
ph = '+44' + ph.substr(1)
}
return {formattedNumber: ph}

jQuery zip masking for multiple formats

I have a requirements for masking a zip field so that it allows the classic 5 digits zip (XXXXX) or 5 + 4 format (XXXXX-XXXX).
I could so something like:
$('#myZipField').mask("?99999-9999");
but the complication comes from the fact that dash should not be showing if the user puts in only 5 digits.
This is the best I came up with so far - I could extend it to auto-insert the dash when they insert the 6th digit but the problem with this would be funny behavior on deletion (I could stop them from deleting the dash but it would patching the patch and so forth, it becomes a nightmare):
$.mask.definitions['~']='[-]';
$("#myZipField").mask("?99999~9999", {placeholder:""});
Is there any out of the box way of doing this or do I have to roll my own?
You don't have to use a different plug-in. Just move the question mark, so that instead of:
$('#myZipField').mask("?99999-9999");
you should use:
$('#myZipField').mask("99999?-9999");
After all, it isn't the entire string which is optional, just the - and onward.
This zip code is actually simple, but when you have a more complex format to handle, here is how it's solved with the plugin (from the demo page):
var options = {onKeyPress: function(cep, e, field, options){
var masks = ['00000-000', '0-00-00-00'];
mask = (cep.length>7) ? masks[1] : masks[0];
$('.crazy_cep').mask(mask, options);
}};
$('.crazy_cep').mask('00000-000', options);
If you're using jQuery already, there are probably hundreds of plugins for masks etc, for example:
http://www.meiocodigo.com/projects/meiomask/
So I don't think you'd have to roll your own
When you use jQuery Inputmask plugin and you want to use 4 or 5 digit values for zip code you should use:
$('#myZipField').inputmask("9999[9]");
Why not have the field be transparent, and have a text object behind it with the form in light grey? So they see #######-#### in the background, and then rig it so the letters dissapear as they type. At that point, it suggests that they should enter a dash if they want to put the extra four, right? Then, you could just rig the script to autoinsert the hyphen if they mess up and type 6 numbers?

Javascript percentage validation

I am after a regular expression that validates a percentage from 0 100 and allows two decimal places.
Does anyone know how to do this or know of good web site that has example of common regular expressions used for client side validation in javascript?
#Tom - Thanks for the questions. Ideally there would be no leading 0's or other trailing characters.
Thanks to all those who have replied so far. I have found the comments really interesting.
Rather than using regular expressions for this, I would simply convert the user's entered number to a floating point value, and then check for the range you want (0 to 100). Trying to do numeric range validation with regular expressions is almost always the wrong tool for the job.
var x = parseFloat(str);
if (isNaN(x) || x < 0 || x > 100) {
// value is out of range
}
I propose this one:
(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)
It matches 100, 100.0 and 100.00 using this part
^100(\.0{1,2})?$
and numbers like 0, 15, 99, 3.1, 21.67 using
^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$
Note what leading zeros are prohibited, but trailing zeros are allowed (though no more than two decimal places).
This reminds me of an old blog Entry By Alex Papadimoulis (of The Daily WTF fame) where he tells the following story:
"A client has asked me to build and install a custom shelving system. I'm at the point where I need to nail it, but I'm not sure what to use to pound the nails in. Should I use an old shoe or a glass bottle?"
How would you answer the question?
It depends. If you are looking to pound a small (20lb) nail in something like drywall, you'll find it much easier to use the bottle, especially if the shoe is dirty. However, if you are trying to drive a heavy nail into some wood, go with the shoe: the bottle with shatter in your hand.
There is something fundamentally wrong with the way you are building; you need to use real tools. Yes, it may involve a trip to the toolbox (or even to the hardware store), but doing it the right way is going to save a lot of time, money, and aggravation through the lifecycle of your product. You need to stop building things for money until you understand the basics of construction.
This is such a question where most people sees it as a challenge to come up with the correct regular expression to solve the problem, but it would be much better to just say that using regular expressions are using the wrong tool for the job.
The problem when trying to use regex to validate numeric ranges is that it is hard to change if the requirements for the allowed range is changes. Today the requirement may be to validate numbers between 0 and 100 and it is possible to write a regex for that which doesn't make your eyes bleed. But next week the requirment maybe changes so values between 0 and 315 are allowed. Good luck altering your regex.
The solution given by Greg Hewgill is probably better - even though it would validate "99fxx" as "99". But given the circumstances that might actually be ok.
Given that your value is in str
str.match(/^(100(\.0{1,2})?|([0-9]?[0-9](\.[0-9]{1,2})))$/)
^100(\.(0){0,2})?$|^([1-9]?[0-9])(\.(\d{0,2}))?\%$
This would match:
100.00
optional "1-9" followed by a digit (this makes the int part), optionally followed by a dot and two digits
From what I see, Greg Hewgill's example doesn't really work that well because parseFloat('15x') would simply return 15 which would match the 0<x<100 condition. Using parseFloat is clearly wrong because it doesn't validate the percentage value, it tries to force a validation. Some people around here are complaining about leading zeroes and some are ignoring trailing invalid characters. Maybe the author of the question should edit it and make clear what he needs.
I recomend this, if you are not exclusively developing for english speaking users:
[0-9]{1,2}((,|\.)[0-9]{1,10})?%?
You can simply replace the 10 by a 2 to get two decimal places.
My example will match:
15.5
5.4366%
1,43
50,55%
34
45%
Of cause the output of this one is harder to cast, but something like this will do (Java Code):
private static Double getMyVal(String myVal) {
if (myVal.contains("%")) {
myVal = myVal.replace("%", "");
}
if (myVal.contains(",")) {
myVal = myVal.replace(',', '.');
}
return Double.valueOf(myVal);
}
None of the above solutions worked for me, as I needed my regex to allow for values with numbers and a decimal while the user is typing ex: '18.'
This solution allows for an empty string so the user can delete their entire input, and accounts for the other rules articulated above.
/(^$)|(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)\.(\.[0-9]{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)/
(100|[0-9]{1,2})(\.[0-9]{1,2})?
That should be the regex you want. I suggest you to read Mastering Regular Expression and download RegexBuddy or The Regex Coach.
#mlarsen:
Is not that a regex here won't do the job better.
Remember that validation msut be done both on client and on server side, so something like:
100|(([1-9][0-9])|[0-9])(\.(([0-9][1-9])|[1-9]))?
would be a cross-language check, just beware of checking the input length with the output match length.
(100(\.(0){1,2})?|([1-9]{1}|[0-9]{2})(\.[0-9]{1,2})?)

Categories

Resources