use of Regular expression - javascript

While using Javascript, I'm making a limit for the product number in front-end.
The product number should be xxxxx 5 digits number or xxx-xxx style 6 numbers.
What I planned was replacing non-correct text characters to "" for each keypress
and called in front like this onkeypress = "checkonlynumdash();"
for the function, my code is like below.
function checkonlynumdash() {
e = window.event;
var keypress = String.fromCharCode(e.keycode);
var numdashkey = "";
numdashkey = /^[-]|[^0-9-]/;
return numkey.test(keypress);
}
while using window.event, I tried to control the real time keypress, but it
does not seem working with replace. Hope someone can point out missing part.

I see two issues:
e.keycode
I would change to
e.charCode
and use another regex: /[\d-]/, it is more simple.
So the result might be:
function checkonlynumdash() {
e = window.event;
var keypress = String.fromCharCode(e.charCode);
var numdashkey = /[\d-]/;
return numdashkey.test(keypress);
}
Also I can't understand your original regexp: /^[-]|[^0-9-]/ symbol ^ means 'in the beginning of the string' or 'not'.

You can try Simple Mask, it is jQuery plug-in to make masks on input fields.
Usage:
$('input').simpleMask({
'mask': ['####-####','#####-####']
});
Demo

Related

How to validate single lines in Html TextAreaFor against regular expression(s)

I am stuck with the following problem. On a web page in my current C# / MVC project, I added some control elements to fill a model. Among these control elements is a text area, designed using #Html.TextAreaFor:
<div class="smt-textarea ">
#Html.LabelFor(m => m.Numbers):
#Html.TextAreaFor(m => m. Numbers, new
{
#class = "form-control",
id = "smt-textarea",
rows = 25,
})
</div>
Users should enter a sequence of numbers into that text area. The number sequence follows a specific pattern. The pattern is later evaluated in code-behind methods, which are working well, and which are not part of my question here.
As a new feature, the numbers entered in the text area should now be validated regarding the amount of numbers in the actual sequence. The rule states that only digits from 0-9 can be entered in the text area. A number sequence should consist of exactly 19 digits.
Since I need to directly access the text area, I figured it might be a good idea to opt for Javascript in this particular case. I should note that I am quite new to JS and this might be one part of the problem. Be that as it may, based on some posts here on SO, I came up with the following preliminary solution.
console.log(textArea.value);
var reg = /\d{19,19}/;
let regex = new RegExp(reg);
if (regex.test(textArea.value)) {
console.log(regex.test(textArea.value));
alert("IT'S A MATCH !!!");
} else {
alert("SORRY, NO MATCH.");
}
}
window.onload = function () {
var textArea = document.getElementById("smt-textarea");
textArea.onkeyup = function (evt) {
evt = evt || window.event;
if (evt.keyCode === 13) {
validateTextArea(this);
}
};
};
Unfortunately, the code seems to validate the entire text area, meaning I do get a match whenever there are one more digit sequences matching the pattern, e.g. when entering the following
12345
0276114931111401167
skjfsjgrs
ksgfskgjsgjsrgs
skjfsjgrs and ksgfskgjsgjsrgs are valid because they are preceded by a "valid" number sequence.
What I would like to accomplish is that upon pressing the <ENTER> key, only the current line of the text area should be validated against the regular expression outlined in the sample. If the current line does not match, a warning message should be displayed. Once the user corrected his/her digit sequence, validation should continue moving to the next line until the next error pops up.
At the moment your validation will be passed if your string from text area contains a sequence from 19 numbers. In order to make sure each line is valid you'd better use ^ and $ anchors to match the whole string from start to end. Something like this:
/^(\d{3}\n?)*$/
var textArea = document.getElementById("smt-textarea");
textArea.onkeyup = function(evt) {
evt = evt || window.event;
if (evt.keyCode === 13) {
validateTextArea(this);
}
};
function validateTextArea(textArea) {
let regex = new RegExp(/^(\d{19}\n?)*$/);
if (regex.test(textArea.value)) {
alert("IT'S A MATCH !!!");
} else {
alert("SORRY, NO MATCH.");
}
}
<textarea name="" id="smt-textarea" rows="25"></textarea>
Also it might be a good idea to trim your string value in order to avoid problems with white-space characters in the end.
Update
Here is another version which validate line by line:
var textArea = document.getElementById("smt-textarea");
textArea.onkeyup = function(evt) {
evt = evt || window.event;
if (evt.keyCode === 13) {
validateTextArea(this);
}
};
function validateTextArea(textArea) {
let lines = textArea.value.trim().split('\n');
let regex = new RegExp(/^\d{19}$/);
let invalid = lines.some(function(line, index) {
let lineInvalid = !regex.test(line);
if (lineInvalid) {
alert(`Line ${index+1} is invalid`);
}
return lineInvalid;
});
console.log(`Text area is ${(invalid ? 'invalid' : 'valid')}`);
}
<textarea name="" id="smt-textarea" rows="25"></textarea>

How to get the -real- last character typed in input with maxlength?

I wanted to know which character the user is typing into an input:
I have an input:
<input maxlength="20"/>
and a script that returns the last typed char:
var eingabe;
$('form').on('keypress', function(event) {
/// if no whitespace:
if (String.fromCharCode(event.keyCode).replace(/\s/g, "").length > 0) {
eingabe = String.fromCharCode(event.keyCode);
$('#eingabe').html("<div>Eingabe : "+ eingabe +"</div>");
}
});
My question is:
because my input has a maxlength attribute, the last typed character on the keyboard is sometimes not the last -real- typed character into the input because the input is "full". How can I get the last character typed into the input?
I haven't tried it, but it must work...
Set onkeypress= or onkeydown= on the Input element and store the key value in a LastChr variable.
I had a similar problem. I wanted to call a function if the user types a specific character into my input field. I solved it with the following:
var input = document.getElementById('myInput');
input.addEventListener('input', function() {
// Get cursor position
var start = this.selectionStart;
// Get last typed character
var lastChar = String.fromCharCode(this.value.charCodeAt(start - 1));
if(lastChar === '[YOURCHARHERE]') {
// do something
}
});
Please keep in mind, that 'input' is only supported down to IE8, but if you don't care about a proprietary browser, you should be fine. I hope this helps.
Inside your function, use the value of the input element to get the last character like $('#input_field').val().substr($('#input_field').val().length - 1) or use your best coding skill to accomplish something similar without accessing the field twice, wink wink.
Use keyup instead:
$('form').on('keyup', function(event) {
var cursorPos = event.target.selectionStart;
var lastTypedChar = elem.target.value[cursorPos - 1];
});

Interactively, don't allow the first character in a text input to be a space, or group of spaces

Firstly, This is NOT a repeat question. Most of the similar questions, I've come across, don't preform the desired action interactively (e.g. "onkeydown", "onkeyup", etc.). I need a pure JavaScript (i.e. NO jQuery) function to disallow the first character of a text-based input to be a space or group of spaces given just the elements ID. Here is what I have:
<script type="text/javascript">
/* Don't allow the first character of a "text-based" input element
* (e.g. text-box, text-area, editable-div's) to be a space, given
* the elements ID ([ eID ]). [BEGIN]
*/
function noPrecedingSpace ( eID )
{
var elmt = document.getElementById(eID);
elmt.addEventListener("keydown", function(event)
{
var strg = elmt.value;
var lastChar = strg.charAt(strg.length - 1);
if ((lastChar == " ")||(lastChar == " ")||(strg == ""))
{
return event.which !== 32;
};
});
};
/* Don't allow the first character of a "text-based" input element
* (e.g. text-box, text-area, editable-div's) to be a space, given the
* elements ID ([ eID ]). [END]
*/
</script>
Any ideas as to why this is not working?
What am I doing wrong?
Please Note: "Paste" is already accounted for, and disallowed on the field by another javascript, that, by the way, is working perfectly.
JSFiddle
Returning true/false is the "old" way of managing event propagation. Better now is to use preventDefault()
var elmt = document.getElementById('noSpaces');
elmt.addEventListener('keydown', function (event) {
if (elmt.value.length === 0 && event.which === 32) {
event.preventDefault();
}
});
This just checks... if the current input length is zero then a space is not allowed.
Also see the fiddle.
You can add/modify to check for non-breaking spaces also, if that's really a problem -- match with a regex like Dave's answer, but only if elmt.value.length is > 0
This, however, would let you type non-spaces, then back-up to the start of the field and insert spaces.
A revised fiddle trims leading whitespace as you're typing, but this also won't entirely solve the problem.
var elmt = document.getElementById('noSpaces');
elmt.addEventListener('keydown', function (event) {
if (event.which === 32) {
elmt.value = elmt.value.replace(/^\s+/, '');
if (elmt.value.length === 0) {
event.preventDefault();
}
}
});
You can keep refining it, even taking the current caret position and the currently selected text into account, but ultimately you must .trim() the string you receive on the server, since I (for one) can send you anything I want to send despite all of your javascript efforts to make me enter a "legal" string.
You can test the value of the input with a regular expression to see if it starts with a space and if so remove the spaces from the start of the value;
var input = document.getElementById('noSpaces');
input.addEventListener('keyup', function(event) {
if(/^\s/.test(input.value)) {
input.value = input.value.replace(/^\s+/,'');
}
});
JSFiddle
Thanks to #StephenP, I have come up with this final answer, which is just perfect for my needs ("visitors_name" field):
<script type="text/javascript">
/* Don't allow the first character of a "text-based" input element (e.g. text-box, text-area, editable-div's, etc.) to be a space, given the elements ID ([ eID ]). Also, don't allow more than one space between adjacent words. [BEGIN] */
/* Usage Example: noPrecedingOrDoubleSpace ("visitors_name"); */
function noPrecedingOrDoubleSpace ( eID )
{
var elmt = document.getElementById(eID);
elmt.addEventListener("keydown", function(event)
{
var strg = elmt.value;
var lastChar = strg.charAt(strg.length - 1);
if ((lastChar == " ")||(lastChar == " ")||(strg == ""))
{
if (event.which === 32)
{
event.preventDefault();
};
};
});
};
/* Don't allow the first character of a "text-based" input element (e.g. text-box, text-area, editable-div's, etc.) to be a space, given the elements ID ([ eID ]). Also, don't allow more than one space between adjacent words. [END] */
</script>
Keep in mind that if you just need no space, only at the beginning of the input, #StephenP's answer is probably more practical, and is the real answer to this question, given the title.
Also remember, that just as #StephenP mentioned, real validation is best done in the server-side script (e.g. php). This JavaScript is just to encourage correct input formatting. Nothing more, nothing less.
Big kudos to #StephenP
Thanks!
Final JSFiddle.

How to remap keyboard within the same textarea

Currently i am doing a project with remapping characters to words by detecting the keyup function. Unfortunately, i have only been able to retrieve the first character and remap to the word i want. In my project, i need to directly retrieve all of my keyboard input and directly convert it to the word that i want within the same textarea. For example when i type in the textarea, it will convert to "are" directly. I don't know why it stopped retrieving the second character and remapping not function. Below is my code, hope someone can tell me my error. Thank you.
<textarea class="width-100" id="translated-text" onkeyup="myFunctionkey(event);" rows="10"></textarea>
<script>
function myFunctionkey(e) {
conversion();
}
function conversion(){
var x = document.getElementById('translated-text');
if(x.value == 'a'){
x.value='yes';
}
if(x.value == 'q'){
x.value = 'are';
}
}
</script>
From what I understand, you only want to grab the input and replace a key stroke with a complete word.
Maybe this will do. I've changed onkeyup to onkeypress because this is more reliable from what I remember.
<textarea id="translated-text" cols="50" rows="10" onkeypress="replaceInputChar(event);"></textarea>
<script type="text/javascript">
//create replacement map
var map = {
"a": "and",
"b": "bold",
"c": "change"
};
function replaceInputChar(e)
{
var ctl = document.getElementById("translated-text"); //control
var char = String.fromCharCode(e.keyCode); //typed char
if (char in map) //check if letter is defined in map
{
//insert replacement instead of letter
if("selectionStart" in ctl)
{
//in modern browsers we can easily mimic default behavior at cursor position
var pos = ctl.selectionStart;
ctl.value = ctl.value.substr(0, pos) + map[char] + ctl.value.substr(ctl.selectionEnd);
ctl.selectionStart = pos + map[char].length;
ctl.selectionEnd = ctl.selectionStart;
}
else
ctl.value += map[char];
if ("preventDefault" in e) //modern browser event cancelling
e.preventDefault();
else
{
//old browser event cancelling
e.returnValue = false; //IE8
return false;
}
}
}
</script>
You should use comparison operator '==' instead of assignment operator '=' while remapping the value, like this:
x.value=='a'
Edit:
You should check the updated code for your problem here:
https://jsfiddle.net/o4coLr5t/1/
Now, the characters you choose to remap in javascript will display the string, that you map the character to. Otherwise it will display nothing on pressing keys. So, try and add all the character keycodes to the javascript code. Hope that helps.

How to avoid parsing address as float in Javascript

I am working on javascript code that parses a tab delimited document. In order to facilitate searching I need to convert those properties that are a number to a float. However, mixed fields (like an address) should maintain the status of a String.
for(var i2=0;i2<line1.length;i2++){
var test = local[i2];
if(! (typeof test === 'undefined')){
test = test.trim();
};
var parsed = parseFloat(test);
if(!isNaN(parsed)){
if(line1[i2] === "Site Address")
console.log("Number before:"+local[i2]+" After:"+parsed);
object[line1[i2]]=parsed;
}
else{
if(line1[i2] === "Site Address")
console.log("before:"+local[i2]+" After:"+test);
object[line1[i2]]=test;
}
}
This seems to work ok unless there are both numbers and chars like the following....
Number before:1752 E MAIN ST After:1752
Is there a way to do this where the above is not seen as explicitly a number?
You can use the unary + operator:
var parsed = +test;
The parseFloat() function is OK with strings that start with a valid number that's followed by non-numeric stuff, as you've discovered.
If that seems too "hackery" you can also use the Number constructor:
var parsed = Number( test );
You haven't provided very much test data, so answers may not be very good. You can try using a regular expression so that only things that look like numbers are treated as numbers, e.g.
var isNum = /^\d+(\.\d+)?$/;
var test = line1[i2];
parsed = isNum.test(test)? parseFloat(test) : test;
The variable "test" would probaby be better named "item" or "value" or similar.

Categories

Resources