Regular expression month validation with text-mask directive - javascript

I'm using text-mask angular2 directive with ionic2.I have a month JS regular expression like this /^(0[1-9]|1[0-2])$/.It is working fine.But now I need to apply this for above directive.I have tried like below.But it is not working.Can you tell me why?
mask: Array<string | RegExp>;
constructor(){
this.mask = [/0[1-9]/, /1[0-2]/];//not working
//this.mask = [/[1-9]/, /\d/]; //this is working
}

Each element in the array imposes restriction on what char a user can input. It seems they are context-unaware. [/0[1-9]/, /1[0-2]/] means the first symbol can consist of 0 and a digit from 1 to 9 and the second symbol should start with 1 and then be followed with 0, 1 or 2 - which is always false.
You may thus use an approximate mask like
this.mask = [/[01]/, /\d/];
The first placeholder will be valid if 0 or 1 is typed, and the second placeholder will be valid for any digit.
And to make sure the month values are typed, I suggest adding pattern="0[1-9]|1[0-2]" for the on-submit validation.

Each element in the mask array restrict on what character a user can input. For example, mark = [/[1-9]/, /\d/] means the user can enter only a number between 1 and 9 in the first placeholder, and only a digit in the placeholders after that.
In your case, each element of your mark (/0[1-9]/, /1[0-2]/) defined an valid pattern for entire input string, not for each character. That why it didn't work.
According to text-mask angular2 document, you can also pass a function as the mask. You should try something like this
this.mask = function(rawValue) {
// add logic to generate your mask array
if (rawValue && rawValue.length > 0) {
if (rawValue[0] == '0') {
return [/[01]/, /[1-9]/];
} else {
return [/[01]/, /[0-2]/];
}
}
return [/[01]/, /[0-9]/];
}

Related

JavaScript regex inline validation for basic calculation string with one operator

I've written a basic 2 operand calculator app (+ - * /) that uses a couple of inline regex validations to filter away invalid characters as they are typed.
An example looks like:
//check if operator is present
if(/[+\-*\/]/.test(display1.textContent)){
//validate the string each time a new character is added
if(!/^\d+\.?\d*[+\-*\/]?\d*\.?\d*$/.test(display1.textContent)){
console.log('invalid')
return false
}
//validate the string character by character before operator
} else {
if(!/^\d+\.?\d*$/.test(display1.textContent)){
console.log('invalid')
return false
}
}
In the above, a valid character doesn't return false:
23.4x0.00025 (no false returned and hence the string is typed out)
But, if an invalid character is typed the function returns false and the input is filtered away:
23.4x0.(x) x at the end returns a false so is filtered (only one operator allowed per calculation)
23.4x0. is typed
It works pretty well but allows for the following which I would like to deal with:
2.+.1
I would prefer 2.0+0.1
My regex would need an if-then-else conditional stating that if the current character is '.' then the next character must be a number else the next char can be number|.|operator. Or if the current character is [+-*/] then the next character must be a number, else the next char can be any char (while following the overall logic).
The tricky part is that the logic must process the string as it is typed character by character and validate at each addition (and be accurate), not at the end when the string is complete.
if-then-else regex is not supported in JavaScript (which I think would satisfy my needs) so I need to use another approach whilst remaining within the JS domain.
Any suggestions about this specific problem would be really helpful.
Thanks
https://github.com/jdineley/Project-calculator
Thanks #trincot for the tips using capturing groups and look around. This helped me write what I needed:
https://regex101.com/r/khUd8H/1
git hub app is updated and works as desired. Now just need to make it pretty!
For ensuring that an operator is not allowed when the preceding number ended in a point, you can insert a positive look behind in your regex that requires the character before an operator to always be a digit: (?<=\d)
Demo:
const validate = s => /^(\d+(\.\d*)?((?<=\d)[+*/-]|$))*$/.test(s);
document.querySelector("input").addEventListener("input", function () {
this.style.backgroundColor = validate(this.value) ? "" : "orange";
});
Input: <input>

use replace to remove chars not existing in a regex match

I'am trying to allow following pattern for a single html input box with javascript regex
-int (aka any minus number so long it not followed by a zero and is in the first position)
0 (a single zero is allowed)
int (is allowed)
I use this function the remove anything that doesn't match it
$('.dointcheck').live('keyup',
function () {
$(this).val($(this).val().replace((/^((?!:([1-9-]?[0-9])).)/g), ''));
if ($(this).val().length == 0) {
$(this).val(0);
}
});
which doesn't work.
Other examples is:
/[^-0-9]/g it removes any non valid chars but doesnt check if the minus is the beginning and is followed by a zero. It allows minus everywhere in the string
(/^((?!:([1-9-]?[0-9])).)/g Don't allow none.
[^1-9-]?[^0-9]* Allow all...
I think I'am missing something.. Any suggestions would be most appreciated..
You may try this regex
^(0).*|^(-?)([1-9]\d*)?.*|^.*
and replace it with $1$2$3 after input
document.querySelector('input').addEventListener('input', ({ target }) => target.value = target.value.replace(/^(0).*|^(-)?([1-9]\d*)?.*|^.*/g, '$1$2$3'));
<input />
It has three tests:
^(0).* // if it starts with 0, discard everything after it
^(-)?([1-9]\d*)?.* // otherwise it can only starts with a -, or any number that is not a 0. Then followed by other digits, then discard everything after it
^.* // if previous rules are not matched, discard everything
In short:
generally only -, 0-9 are allowed.
if you type a 0 first, nothing will be allowed after.
if you type a 1-9 first, only numbers are allowed after.
if you type a - first, only 1-9 is allowed next, then any digit is allowed after.
I changed your regexp and made it a bit more modular and it worked fine.
function toValidNumber(int) {
return (/^\s*[+-]?(\d+|\d*\.\d+|\d+\.\d*)([Ee][+-]?\d+)?\s*$/).test(int) ? int : 0;
}
$('.dointcheck').live('keyup',
function () {
$(this).val(toValidNumber($(this).val()));
});
Orginal RegEXP in Stackoverflow

Regex to extract arguments passed into string '#substr( , , )'

we have a text input where the user can enter some text and apply some functions on top of the text like ( substr , replace ) etc. For example user can enter the text "hello" in the text input and can apply the substring function ( #substr(hello, 'startIndex', 'length'))and can mention the start index and the length etc.
Need to use the regex to extract the values passed into the #substr function for validating the mandatory fields. For example 'start index' and 'length' is required when the user selects the substr function.
Below are the different scenarios and its expected output .
#substr(hello,1,3) ---> ['hello','1','3']
#substr($(sometext),1,3) ---> ['$(sometext)','1','3']
#substr(#trim(hello),1,3) ----> ['#trim(hello)','1','3']
#substr(#replace(hello-world,hello,hi),1,3) ---> ['#replace(hello-world,hello,hi)','1','3']
As from the above examples need to extract the arguments passed into the #substr function as array elements.
Tried this regex
/#substr\((.*?),(.*?),(.*?)\)/g
This fails when we have a nested functions like this - #substr(#replace(hello-world,hello,hi),1,3)
You could use the below regex with capturing groups.
#(\S+?)\((.*)\,(\d+),(\d+)\)
For nested matching, it is not impossible, but much complex in regex. The easy approach should be avoiding regex and using js code for nested matching.
This regex can solve your problems, if the string takes up an entire line, but if you enter comma commands in the second argument, it will fail, this is a very complex problem to solve with simple regex. I think you're knocking on the compilers' door.
regex = /^#substr\((.*),(.*),(.*)\)$/;
text = "#substr(#replace(hello-world,hello,hi),1,3)";
console.log(regex.exec(text));
If you're trying to get the length of user input or index, you could put all the desired methods inside a function or multiple functions that call be called on button-click.
https://www.bitdegree.org/learn/javascript-input
I may be misunderstanding but if I take one of your examples:
#substr(hello,1,3) ---> ['hello','1','3']
When I run
str = "hello world"
str.substring(1,3) --> I get "el" (not "hello", "1", "3")
Get some text:
var firstName = document.getElementById("firstName").value;
var age = document.getElementById("age").value;
Click a button to call your function.
function doSubstringStuff(textValue, subString_mode) {
if subString_mode == "length" {
return textValue.length;
}
OR
Validate the length matches your criteria.
if (textValue.length > 10) {
alert("The name must have no more than 10 characters");
Or Perform other tasks, determined by the argument "mode"
else if subString_mode == "integer_test"{
if (isNaN(textValue) || age < 12 || age > 100){alert("The age must be between numbers 12 and 100")};

Validation to check if the user has entered the correct format

I have a dynamic grid that has a numeric field in which I have applied masking. Also it has a plus button means the user can add many rows as he wants. The masking is applied like this:
<input type='textbox' placeholder='00000-00-000' data-mask='00000-00-000'
This masking is applied when the user enters 10 digit number but it lets the user enter a 2 or 3 digit number as well. For this I am trying to apply validation while saving so that it checks whether the value entered matches the required format.
What I have done so far is :
value = $(this).find('td:eq(1)').find('input').val(); //saves the entered value in a variable value
myRegExp = new RegExp(/\d{5}-\d{2}-\d{3}/);
if (!myRegExp.test(value)) {
valid = false;
}
else
valid = true;
The value that user enters is saved in varaible called value and then I have defined my Regex Expression to match my value with that expression but somehow this regex expression is not working. Is this the correct way to define regex expression? What am I missing here? My required format is 00000-00-000. Any help would be appreciated.
Your logic is correct but you have not defined the end point that's why it allows to insert more values.
In your Regex it only checks if the 10 digits are in the specific order
try out this
myRegExp = new RegExp(/^\d{5}-\d{2}-\d{3}$/);

how to use javascript to check if the first character in a textbox is a number?

I'm making a simple form and having a textbox for street address....
All I want to do is check if the first value entered is a number or not.
How can I do it?
if(document.forms[0].elements[2].value.
that is all I have now but I'm not sure what I should add to it to check the first character only.
As you said in your question you want to check for the first character only, you can use charAt function for string to check whether the first character is from 0 to 9 or any other check you want for the first character
Possible solution
var firstChar = document.forms[0].elements[2].value.charAt(0);
if( firstChar <='9' && firstChar >='0') {
//do your stuff
}
This can simply use isNaN. Just put a bang before it to check if it is a number, instead of isNaN's normal use of checking if it isn't a number, like so:
var val = document.forms[0].elements[2].value;
if (!isNaN(val.charAt(0))){ //If is a number
//Stuff
}
This also goes with numbers as strings, so need to worry about quotes or any of that hoo ha.
You can use if (document.forms[0].elements[2].value.match(/^\d+/)) to check if the beginning of the field is composed by numbers.
It will match for:
0 - valid
1 - valid
1a - valid
1 a - valid
1234567 - valid
a - invalid
a1 - invalid
Literally anything that start with numbers.
You can extend its functionality to if (document.forms[0].elements[2].value.match(/^\d+ +.+/))
In this form it will now require that its a number, plus one or more spaces, followed by anything else.
0 - invalid
1 - invalid
1(space) - invalid
1 1 - valid
1 a - valid
12345 abcdef - valid
Read more about Regular Expressions to elaborate complexier checkings.
But remember first that not every address has numbers, and most countries in the world don't use this format of writing addresses. As for the address field, I believe you should leave it open to be written in however format the user wish.

Categories

Resources