Detecting Period Symbol as not Valid against Number Input Pattern Using JavaScript - javascript

I have an input tag of type number with pattern validation attached to it that has at least taken care of eliminating the 'e' '+' '-' characters from being input. However the '.' symbol still gets through for some reason. Here are the relevant portions of code from my program:
<input type="number" id="job-priority" min="1" max="99" pattern="[0-9]+" placeholder="1 (High) — 99 (Low)" style="width:186px; padding-left:14px; text-align:center;">
document.getElementById('job-priority').addEventListener('input', function () {
// Check that characters typed into job priority field are valid.
if (!document.getElementById('job-priority').validity.valid) {
var value = document.getElementById('job-priority').value;
value = value.slice(0,-1);
document.getElementById('job-priority').value = value;
}
});
document.getElementById('job-priority').addEventListener('change', function () {
// Check that number entered into job priority stays within limits.
var value = Number(document.getElementById('job-priority').value);
var min = Number(document.getElementById('job-priority').min);
var max = Number(document.getElementById('job-priority').max);
if (value < min)
document.getElementById('job-priority').value = min;
else if (value > max)
document.getElementById('job-priority').value = max;
});
From my own research on this up to this point, I have come across one previous question post on StackOverflow regarding input patterns with input type number. That post, in short, confirms that input patterns don't work for input type number. It proposes the solution to just use input type text instead with a pattern to allow only numbers through. However, I want to keep the input type to number because of the up/down arrows that increase/decrease the number in the input field. I would be willing to change the input type to text only if their is a way to keep the up/down arrows in question.
I also see that if I remove the pattern from the input tag, my event listener for 'input' still successfully takes care of not allowing the 'e' '+' '-' characters somehow. Of course, the '.' symbol is still being allowed when it shouldn't. So I guess at least I confirmed that the pattern wasn't actually doing anything from what I can tell.
More specifically, if the '.' is typed as the first character, the validation check successfully works and nothing appears in the input field which is the desired behavior. However, if the first character typed is a number and then second character typed in is the '.' symbol, then for some reason the '.' symbol appears when it should not have.

Figured out a solution to my problem.
document.getElementById('job-priority').addEventListener('input', function () {
// Check that characters typed into job priority field are valid.
document.getElementById('job-priority').type = 'text';
if (!document.getElementById('job-priority').validity.valid) {
var value = document.getElementById('job-priority').value;
value = value.slice(0,-1);
document.getElementById('job-priority').value = value;
}
document.getElementById('job-priority').type = 'number';
});
You'll see that what I did was change the input type to 'text' temporarily just for the input validation. Then, as soon as it's done, immediately change the input type back to 'number'.

Related

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}$/);

Regular expression month validation with text-mask directive

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]/];
}

Determine if user is typing character by character or if more than 1 character is entered

I need to determine if a user is typing character by character into a text field or using browser autocomplete / pasting more than 1 character in javascript / jQuery.
I need to use the input method to determine the browser autocomplete:
$('input[type=text]').input(function(){
var a = this.value; // input value
var b = a.length; // amount of chars
$.each(a, function(i, j) {
// Loop through the input value each time after something is entered
}
});
I think I need the length of the last input value, so if it's = 1 typing is assumed or if it's more than 1 pasting / autocomplete is assumed.
Technically, 1 character can be pasted but no need to worry about that for now.
Thanks.
You'll need to handle the keyup event and track the length of the input string between the current keyup and the prior. If the difference in the string's length is greater than 1, then you know it was either the result of the auto-complete or pasted input.

Limiting a textbox to digits OR one of two non repeating strings only using regular expressions

I am trying to constrain a textbox to either digits OR one of two special string cases: "na" or "tx". If digits exits in the input, "na" and "tx" are invalid and should not be allowed in the input box. if "na" or "tx" exists, digits should not be allowed.
I am very new to reg expressions but is it possible to construct this? Here is what I have so far:
event.sender.element.find("input").keyup(function () {
this.value = this.value.replace(/((?!na)|([^0-9]))/g, '');
});
Using basic online examples, I know how to limit the input to purely digits. My current set of requirements, however, is making this very challenging for me.
string = string.replace(/^(n(a?|$)|t(x?|$)|[0-9]*).*$/g,'$1');
Though, generally, using onkeypress & onchange events in tandom yield better results: the first prevents the 'flickering' of the invalid characters, the second prevents changing it by pasting in data with the mouse for instance. See also: How to prevent number input on keydown As always: revalidate it on the server.
$('input').keyup(function () {
var a = $(this).val();
if (a.match(/^tx/)) {
a = 'tx';//set manually
} else if (a.match(/^na/)) {
a = 'na';//set manually
} else if(a.match(/[\d]/)) {
a = a.replace(/[^0-9]+/g, '');//replace all but numbers
} else if (a.match(/^[nt]/)) {
a = a.replace(/^([tn])([a-zA-Z])+$/,'$1');//replace with first letter
} else {
a = '';//matches nothing equals nothing
}
$(this).val(a);//print new value
})
It uses regex to remove any undesired input, and provides reporting on the demo. If it doesn't start with 'tx' or 'na', but does have a number it switches to number mode, and if it does begin with either of them then it's hard set to them. If nothing matches, it empties out.
EDIT
Although my answer produced the correct result, it wasn't as simple as it should be with regex.
So I added Wrikkens regex as well, since it's easier:
http://jsfiddle.net/filever10/FQ5aD/
The biggest difference i see in functionality is with strings like "t5", on wrikkens, that gets changed to "t", and on mine that triggers number mode and will change to "5".
This allows it to fit the parameters of the problem. Since neither 'tx' or 'na' exist at that point, numbers should take over because 't' and 'n' don't match anything yet, but a number does; since it only needs one character to match as a number, and the others need 2 for a match.

Only allowing ints and floats to be entered into field with javascript and mootools

I require some sort of direction with how to only allow either an int or float to be entered into a form input field. The validation must happen on the key up event. The problem I am having is that when entering, for example, 1.2 the check within the keyup event function sees 1. which is not a number.
Here is the code I have:
document.id('inputheight').addEvent('keyup', function(e) {
this.value = this.value.toFloat();
if (this.value == 'NaN') {
this.value = 0;
}
});
Any help is appreciated!
You could simply clean up the value of the field on keyup. Something like this should do the trick:
this.value = this.value.replace(/([^\d.]+)?((\d*\.?\d*)(.*)?$)/, "$3");
The regular expression instantly replaces the value with the first numeric string it encounters.
([^\d.]+)? // optionally matches anything which is not
// a number or decimal point at the beginning
(\d*\.?\d*) // tentatively match any integer or float number
(.*)?$ // optionally match any character following
// the decimal number until the end of the string

Categories

Resources