Regex to go beyond 10 numbers - javascript

Trying to match with regex, it has to be a number and it shouldn't go beyond 10 numbers. Anything else don't show!
match(/[^0-9]|[0-9]{10,80}/)
The first part works, meaning it's NOT a number, but the second part doesn't, if it's above 10.
http://jsfiddle.net/qwtmnuey/1/
I can do it in another way but I want it the regex way.. thank you!
(function($){
$('input').on( 'keypress', function(e){
var char = String.fromCharCode(e.keyCode);
if ( char.match(/[^0-9]|[0-9]{10,80}/) ) {
e.preventDefault();
}
});
})(jQuery)
HTML:
<input type="text">

You're checking if char matches the regex, but you mean to check if the entire contents of the input match your regex. If you add id="myinput" to your <input> and in your javascript you add
var inputdata = document.getElementById("myinput").value;
Then you can check if inputdata matches your regex it does work.
Also you're checking for {10,80} which means between 10 and 80 but you can also change that to {10,} which means 10 or more

Related

Javascript regExp Input Validation

This is my first post and i think the answer is very easy but i don't get it:
I (try) to build a shopify store but i have to make some modifications and here is the point at where i am stuck:
On my Product Page i want to inluce a <input type=text>, which is required, can only be Capital Letters and the length must min. be 1 and max. 10. I tried it with html5 pattern but it didn't worked. I read something, that if the shopify theme includes ajax, it just ignores the pattern and the required attribute (i don't know if this is true).
So i tried to make my own functions:
$('#dein-text').on("change textInput input", function(evt) {
$(this).val(function (_, val) {
return val.toUpperCase();
});
});
this just should return the string into capital letters.
function checkText() {
var re = /(?=.*[A-Z]).{1,6}/;
if(re.test($('#dein-text').val())) {
$('#problem-bei-input').hide();
$('.add', $product).removeClass('disabled').removeAttr('disabled');
} else {
$('#problem-bei-input').show();
$('.add', $product).addClass('disabled').attr('disabled', 'disabled');
}
}
this function is executed at every change on the input form:
$('#dein-text').on("change textInput input", checkText);
This does not work, because it removes the disabled class if there is min. 1 letter (it does not check if there are more than 6) and if there is one capital letter (something like "HA11" does not add the (.disabled) class).
i hope i could describe what my problem is.
Thank you for your help!
edit: this is the .liquid code of the whole form:
https://codepen.io/shawdyy/pen/PmOPWy
(i hope you can see this on codepen, sry i am really new to the webdev thing)
You can try:
$('#my_id').on("change input", function(evt) {
$(this).val(function (_, val) {
return val.toUpperCase().replace(/[^A-Z]/, "").replace(/^([A-Z]{1,10}).*$/g, "$1");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="my_id">
To only allow one to ten uppercase ASCII letters in the input field use the following HTML5 pattern:
<input type="text" pattern="[A-Z]{1,10}" title="Only 1 to 10 uppercase ASCII letters allowed!">
If you need to match a string that only contains 1 to 10 uppercase ASCII letters in plain JS, you need
 var re = /^[A-Z]{1,10}$/;
Note that start and end anchors (^ / $) are added by the HTML5 automatIically when using the regex in the pattern attribute.

Jquery/Regex not applying to val / var?

I'm doing something wrong, that's for sure :-) I checked https://regex101.com/ to check if the Regex is correct and couldn't find any problems. Also I'm pretty new to jQuery/JavaScript but the console isn't firing any Syntax errors etc.
I tested the code to replace 'Goedemorgen' to 'Goodmorning'. that worked fine so I guess the fault is within the replace/regex? I'm not sure! Any help would be appreciated.
$( document ).ready(function() {
$(".wpcf7-number").focusout(function() {
var InputVal = $('.wpcf7-number').val();
var InputValNew = InputVal.replace(/^[0-9]*$/g,'');
console.log(InputValNew + ' New Var');
});
});
The output I wish to get:
033-2245-22455 to: 033224522455 (so without the -).
Don't be harsh I'm still learning!
You want to remove all characters that are not digits.
You need to move ^ into the character class (at the beginning) so that it negates the meaning of the range, and remove quantifier and anchors.
var InputValNew = InputVal.replace(/[^0-9]/g,'');
Here is the regex101.com demo
You regex - /^[0-9]*$/g - matches a whole string that is either empty or only contains digits. ^ here is a start of string anchor, and $ is the end of string acnhor. * means *0 or more occurrences. So, /g global modifier is meaningless: you cannot have multiple matches if you pass 1 string and want to match it fully.
There is also \D class matching any non-digit character. It is an absolute synonym of [^\d] or [^0-9] in JS.
You can use \D to match any none digit value
$(document).ready(function() {
$(".wpcf7-number").focusout(function() {
var InputVal = $('.wpcf7-number').val();
var InputValNew = InputVal.replace(/\D/g, '');
console.log(InputValNew + ' New Var');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type=text class="wpcf7-number" />
Sample code which will work for you
var a ="033-2245-22455";
var b =a.replace(/-/g ,'');
alert(b);

Regular expression. Find three words in the field

Help make the correct regular expression for the search 3 words into the field. So far I have done so, but I think it's crazy.
var inp = document.getElementsByTagName('input')[0],
button = document.getElementsByTagName('button')[0];
button.onclick = function() {
console.log(inp.value.match(/^([а-яa-z0-9]+ ){2}[а-яa-z0-9]+/i));
};
<input type="text" />
<button>Check</button>
I guess it's easier to split the text and then verify that the element count is as you expect it. You may want to trim the text before to avoid leading and trailing empty strings in the result array.
console.log(inp.value.trim().split(/\s+/))

Regex to validate a password [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Password validation regex
between 8 and 16 characters, with at least 1 character from each of the 3 character classes -alphabetic upper and lower case, numeric, symbols.
I have this code, but it doesn't work, when I write more than 16 characters, gives it as valid, but it should not; the it should to work ok with 3 character classes, but it works with 4, where's my mistake??
http://jsbin.com/ugesow/1/edit
<label for="pass">Enter Pass: </label>
<input type="text" id="pass" onkeyup="validate()">
Script
function validate() {
valor = document.getElementById('pass').value;
if (!(/(?=.{8,16})(?=.*?[^\w\s])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*/.test(valor))) {
document.getElementById('pass').style.backgroundColor = "red";
} else {
document.getElementById('pass').style.backgroundColor = "#adff2f";
}
}
Regular expressions are not a panacea. It's not too hard to do it, mixing with regular code:
function validatePassword(password) {
// First, check the length.
// Please see my comment on the question about maximum password lengths.
if(password.length < 8 || password.length > 16) return false;
// Next, check for alphabetic characters.
if(!/[A-Z]/i.match(password)) return false;
// Next, check for numbers.
if(!/\d/.match(password)) return false;
// Next, check for anything besides those.
if(!/[^A-Z\d]/i.match(password)) return false;
// If we're here, it's valid.
return true;
}
However, I'd look into something like zxcvbn, a password checker, which I think is a better password quality checker, checking things like common dictionary words after un-13375p3/-\kification and dealing with entropy decently. It is used, among others, by Dropbox. Try it here.
You need to anchor the match to the beginning of the string, and anchor the first lookahead to the end:
^(?=.{8,16}$)
Also, the last lookahead needs to be split in two:
(?=.*?[A-Z])(?=.*?[a-z])
Why don't you just test for the three character sets with regular expressions:
[A-Za-z0-9]+
Then count the length of the string to validate the length.
What about this range:
/[A-Za-z0-9$-/:-?{-~!"^_`\[\]]/
So you can check first
/[A-Za-z]+/
then
/\d+/
and finally
/[$-/:-?{-~!"^_`\[\]]+/
If it passes you can check the length.
You can see this link to see why the symbols work.

Using Regular Expressions with Javascript replace method

Friends,
I'm new to both Javascript and Regular Expressions and hope you can help!
Within a Javascript function I need to check to see if a comma(,) appears 1 or more times. If it does then there should be one or more numbers either side of it.
e.g.
1,000.00 is ok
1,000,00 is ok
,000.00 is not ok
1,,000.00 is not ok
If these conditions are met I want the comma to be removed so 1,000.00 becomes 1000.00
What I have tried so is:
var x = '1,000.00';
var regex = new RegExp("[0-9]+,[0-9]+", "g");
var y = x.replace(regex,"");
alert(y);
When run the alert shows ".00" Which is not what I was expecting or want!
Thanks in advance for any help provided.
strong text
Edit
strong text
Thanks all for the input so far and the 3 answers given. Unfortunately I don't think I explained my question well enough.
What I am trying to achieve is:
If there is a comma in the text and there are one or more numbers either side of it then remove the comma but leave the rest of the string as is.
If there is a comma in the text and there is not at least one number either side of it then do nothing.
So using my examples from above:
1,000.00 becomes 1000.00
1,000,00 becomes 100000
,000.00 is left as ,000.00
1,,000.00 is left as 1,,000.00
Apologies for the confusion!
Your regex isn't going to be very flexible with higher orders than 1000 and it has a problem with inputs which don't have the comma. More problematically you're also matching and replacing the part of the data you're interested in!
Better to have a regex which matches the forms which are a problem and remove them.
The following matches (in order) commas at the beginning of the input, at the end of the input, preceded by a number of non digits, or followed by a number of non digits.
var y = x.replace(/^,|,$|[^0-9]+,|,[^0-9]+/g,'');
As an aside, all of this is much easier if you happen to be able to do lookbehind but almost every JS implementation doesn't.
Edit based on question update:
Ok, I won't attempt to understand why your rules are as they are, but the regex gets simpler to solve it:
var y = x.replace(/(\d),(\d)/g, '$1$2');
I would use something like the following:
^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)$
[0-9]{1,3}: 1 to 3 digits
(,[0-9]{3})*: [Optional] More digit triplets seperated by a comma
(\.[0-9]+): [Optional] Dot + more digits
If this regex matches, you know that your number is valid. Just replace all commas with the empty string afterwards.
It seems to me you have three error conditions
",1000"
"1000,"
"1,,000"
If any one of these is true then you should reject the field, If they are all false then you can strip the commas in the normal way and move on. This can be a simple alternation:
^,|,,|,$
I would just remove anything except digits and the decimal separator ([^0-9.]) and send the output through parseFloat():
var y = parseFloat(x.replace(/[^0-9.]+/g, ""));
// invalid cases:
// - standalone comma at the beginning of the string
// - comma next to another comma
// - standalone comma at the end of the string
var i,
inputs = ['1,000.00', '1,000,00', ',000.00', '1,,000.00'],
invalid_cases = /(^,)|(,,)|(,$)/;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].match(invalid_cases) === null) {
// wipe out everything but decimal and dot
inputs[i] = inputs[i].replace(/[^\d.]+/g, '');
}
}
console.log(inputs); // ["1000.00", "100000", ",000.00", "1,,000.00"]

Categories

Resources