I need to validate some user input with javascript. I need to check that their entry (value) is of the correct type (type).
I need my regex pattern to make sure values only contain numbers and nothing else, except measurment types can also contain decimal points.
What is the correct way to do this? My way seems like it may be, but i am guessing. In any case, something is wrong with my regular expression patterns as it is throwing the error stated in the code comment.
Here is my code:
function validateInput(value, type) {
console.log(value);
if(type === "Integer"){
var patt = new RegExp("^\D", i);
}
else if(type === "Measurement"){
var patt = new RegExp("^\D", i); //Uncaught SyntaxError: Invalid flags supplied to RegExp constructor '2'
}
else{
return true;
}
if(patt.test(value)){
return false;
}
else{
return true;
}
}
function sendObs() {
RID = $("#oid").val();
console.log(RID);
var children = $("#abc").children();
var xmlString = "<root><rid>" + RID + "</rid>";
for(i=0; i < children.length; i++){
var value = children[i].children[0].value;
var type = children[i].children[0].id;
var validationResult = validateInput(value, type);
if(!validationResult){ //calling the validation method here
alert("invalid entry");
return;
}
var code = children[i].children[0].className;
xmlString += '<question><code>' + code + '</code><value>' + value + '</value></question>'
}
xmlString +='</root>'
console.log(xmlString);
data = $.parseXML(xmlString);
console.log(data);
//send it here
}
Instead of using regular expressions, you could just call parseInt() and parseFloat().
On top of converting your strings to workable numbers, both functions return NaN if the input is invalid.
number = parseFloat(string)
if (isNaN(number)) {
# `string` is invalid
}
Related
My goal is to edit the string (which has an email) to mask the first part, like say the email is johndoe#abc.com then I should output j*****e#abc.com.
var maskPII = function(S) {
var ans = "";
if(S.includes("#")){
S = S.toLowerCase();
var parts = S.split("#");
var first = parts[0];
for(var i=0;i<parts[0].length;i++){
if(i!=0 && i!=parts[0].length - 1)
first[i] = '*';
}
ans = first +"#" +parts[1];
}else{
}
return ans;
};
However in my loop I can't change the characters to asterisks.
After execution I see value of first still same as parts[0] and has no asterisks, can some one explain why? Also, what would I need to do to modify the variable inside loop?
To answer your question... javascript allows you access values of a string using [] indexing.. but that is read only access... you cannot insert/replace values using that operator.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
When using bracket notation for character access,
attempting to delete or assign a value to these properties will not succeed.
The properties involved are neither writable nor configurable.
(See Object.defineProperty() for more information.)
You need to extract the values you want to keep from the existing string and build up a new string as noted in other answers...
Well, this's what you're looking for, and this will be the output j*****e#abc.com.
var ans = "";
var S = "johndoe#abc.com"; //example
S = S.toLowerCase();
var parts = S.split("#");
var first = "";
for(var i = 0; i < parts[0].length; i++){
if(i != 0 && i != parts[0].length - 1){
first += '*';
}else{
first += parts[0][i];
}
}
ans = first +"#"+ parts[1];
console.log(ans);
Here is the code with your approach:
var maskPII = function(S) {
var ans = "";
if(S.includes("#")){
S = S.toLowerCase();
var parts = S.split("#");
var first = parts[0][0];
for(var i=0;i<parts[0].length;i++){
if(i!=0 && i!=parts[0].length - 1)
first += '*';
}
ans = first + parts[0][parts[0].length - 1] +"#" +parts[1];
}else{
}
return ans;
};
But if i were you i would use:
var mail = "johndoe#abc.com";
mail = mail.replace(/(?<=.)(.+?)(?=.#)/gi, '*'.repeat(mail.split('#')[0].length - 2));
console.log(mail);
You can use the bracket notation on a string (like an array) to get the character at a specific index, but you can't use this to change characters. So first[i] = '*' in your code wont do anything.
Strings in JavaScript are immutable. This means that if you want to change a string, a new string instance will be created. This also means that when you change a string in a for-loop, it can impact performance. (Although in this case the difference wont be noticeable.
)
I would use this code:
function maskPII(str) {
const indexOfAt = str.indexOf('#');
if (indexOfAt <= 2) {
return str;
}
return str[0] + '*'.repeat(indexOfAt - 2) + str.substring(indexOfAt - 1);
}
const email = 'johndoe#abc.com';
console.log(email);
console.log(maskPII(email));
It will look for the index of the # sign. If the index is less or equal than 2, (when not found the index will be -1) it will return the original string.
Otherwise it will get the first character, calculate the amount of asterisks needed (index of the # sign -2) and repeat those and then add the rest of the original string.
I am trying to validate the password using javascript regex. Now I want to validate two lower case letters (2 small letters) which is coming from json.
psw.onkeyup = function() {
var Lcase = jsonData.LOWERCASE;
var psw = document.getElementById("password");
var lowerCaseLetters = /[a-z]{2}/g;
if(psw.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
}
In the above code I am setting up a variable "Lcase" to json data and now I want to replace "{2}" (inside regex) with that variable "Lcase" coz the "Lcase" variable is dynamic. If I am doing something wrong then please guide me to come out of this problem.
I want to validate small case letters which is coming from json(dynamic number) to see how many small letters are there in the password string.
For your information the below code for password length is working.
if(psw.value.length >= jsonData.MINLEN_RANGE) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
If define your regular expression using RegExp, you can define {2} using Lcase.
This code also includes the question posted on the comments bellow.
psw.onkeyup = function() {
var Lcase = jsonData.LOWERCASE;
var psw = document.getElementById("password").value.replace(/([a-z])\d+/g, '$1');
var lowerCaseLetters = new RegExp('[a-z]{' + Lcase + '}', 'g')
if(psw.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
}
I am trying to add validation to my code (as my brother puts it) and that it should only accept numbers and not letters as it moves through the array. I have tried different methods but it still accepts letters and if it doesn't it crashes at array[1].
here's the part of my code:
public static void main(String[]Terminal) {
String Choice;
char response1;
String response = null;
String Display = null;
String TryAgain = null;
String Element = null;
boolean Validation = true;
int numberOfElements = 5; //array element numbers
int index;
int Choice1;
int[] Array = new int[numberOfElements]; //array
do { // Rewind Option
do {
for (index = 0; index < numberOfElements; index++) { // Loop for Array Input
if(index==0) //Dialog Design, tied to Loop
{Element = "First";}
else if
(index==1) {Element = "Second";}
else if
(index==2) {Element = "Third";}
else if
(index==3) {Element = "Fourth";}
else if
(index==4) {Element = "Fifth";}
response = JOptionPane.showInputDialog(null, "Enter the " + Element + " (" +(index+1)+ "): " ); //Display Dialog
// the validation should be here right?
}
int Array1 = Integer.parseInt(response);
Array[index] = Array1;
I understand what you want to do but I'm not really sure what the ultimate purpose of your code is for. The reason I ask is that there may be a possibility that a ComboBox with a numerical list may be better suited for your InputBox dialog.
As you know your Input Box dialog will return a string. You need to ensure that what was entered was in fact a numerical value. To do this you can use the String#matches() method along with a Regular Expression, for example:
while(true) {
//Display Dialog
response = JOptionPane.showInputDialog(null, "Enter the " + Element +
" (" +(index+1)+ "): " );
if (!response.matches("\\d+") {
JOptionPane.showMessageDialog(null, "The data you entered is not a
valid Numerical Value (" + response + ").",
"Invalid Input", JOptionPane.WARNING_MESSAGE);
continue;
}
break;
}
I have a problem here with validating user's input in textarea.
A user is suppose to enter his description in one of the textarea feild in form. But some people just put the random text like 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' or something to bypass the minimum length requirement.
Now i want to prevent user from typing such long text without any spaces since it disrupts the UI of my page.
Also a long text entered by user without any spaces can be a valid url too. So how do i manage this & throw a error to user to correct the text only if it is too long and it isnt a valid url ??
PS: I dont want to split string myself.. I just want to detect it and throw error to user on client side validation. Just to put end to some doubts, i will do server side validation in which i will forcibly enter a space and save it in DB. But i am expecting to solve this problem on client side
var STRING_MAX_LENGTH = 10;
var description = 'aaa aaaaaaaaaa bbbbbbbbbb http://www.google.com/search?q=client-side-filtering';
var array = description.split( ' ' );
$.each( array, function() {
if ( this.length >= STRING_MAX_LENGTH ) {
if( /^([a-z]([a-z]|\d|\+|-|\.)*):(\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*#)?((\[(|(v[\da-f]{1,}\.(([a-z]|\d|-|\.|_|~)|[!\$&'\(\)\*\+,;=]|:)+))\])|((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=])*)(:\d*)?)(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*|(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*)?)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)*)*)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)){0})(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|#)|\/|\?)*)?$/i . test( this ) ) {
alert( this + ' is an URL' );
} else {
alert( this + ' is not an URL' );
}
}
});
http://jsfiddle.net/vVYAp/
function validate()
{
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var wordLengthExpr = /\b[^\s]{50,}\b/;
var regex = new RegExp(expression);
var wordLengthRegex = new RegExp(wordLengthExpr);
var t = $("#myTextarea").val();
if (t.match(regex) || !t.match(wordLengthRegex))
{
//valid
}
else
{
//throw error
}
}
This is a two step process:
Determine if any words are too long.
If so, determine if they are valid URLs.
var validateWordLength = function (str) {
var maxLength = 50, // or whatever max length you want
reURL = /^(ftp|http|https):\/\/[^\s]+$/, // use whatever regular expression for URL matching you feel best
words = str.split(/\s+/),
i;
for (i = 0; i < words.length; i += 1) {
if (words[i].length > maxLength) {
// test for url
// but bear in mind the answer at http://stackoverflow.com/questions/1410311/regular-expression-for-url-validation-in-javascript
// testing for url may not be fruitful
if (!reURL.test(words[i])) {
return false;
}
}
}
return true;
};
try this
var value = Your text;
var result = value.replace(" ","");
if(value.length == result .length)
//not valid
else
//valid
You can get length of each word, and then can decide whether to allow the user or not -
var arr = text.split(' ');
$.each(arr,function(){
console.log(this.length);
// check valid word length
});
http://jsfiddle.net/mohammadAdil/cNZtn/
If you use the jQuery validate plugin you can add a method to it:
jQuery.validator.addMethod("samechars", function(value, element) {
return this.optional(element) || !/([a-z\d])\1\1/i.test(value);
}, "Invalid input");
If you want to use jQuery you can use the following:
$("form").submit(function(e){
var $textarea = $('#msg'),
maxWordLength = 20;
var value = $textarea.val().split(' '),
longWord = false;
for(var n = 0; n < value.length; n++) {
if(value[n].length >= maxWordLength)
longWord = true;
}
if(longWord) {
alert('Too long word');
return false;
}
});
Here is a fiddle:
http://jsfiddle.net/pJgyu/31286/
I have a text box where the value is the result of a calculation carried out in jQuery. What I would like to do, using jQuery, is to display brackets around the number in the text box if the number is negative.
The number may be used again later so I would then have to remove the brackets so further calculations could be carried out.
Any ideas as to how I could implement this?
Thanks
Zaps
function FormatTextBox(id) {
var txtBox = $(id).val();
//strip bracket to get the number only
txtBox = txtBox.replace("[", "").replace("]", "");
var val = parseFloat(txtBox);
if (val < 0) {
txtBox.val("[" + val + "]");
} else {
txtBox.val(val);
}
return val;
}
First, store your calculation in a variable. You shouldn't be using the DOM to store data (in most cases). This basically eliminates your problem.
Number.prototype.bracketed = function() {
if(this < 0) {
return '[' + -this + ']';
} else {
return '' + this;
}
};
var result = do_calculation();
myTextBox.value = result.bracketed();
// result still holds the original Number value.
If you really want to store the data as the .value of the text input, you can make an unbracketed function as well:
String.prototype.unbracketed = function() {
var parts = this.match(/^\[([0-9]+)\]$|^([0-9]+)$/); // [number] or number
if(parts[1]) { // [number]
return -parseInt(parts[1], 10);
}
if(parts[2]) { // number
return parseInt(parts[2], 10);
}
return NaN;
};
Assuming you might have multiple fields (and you don't want the negative sign):
jQuery('input').each(function(){
if(jQuery(this).val() < 0 ){
jQuery(this).val('['+-1*jQuery(this).val()+']');
}
}
)
Then when you grab the value again, just strip the brackets and multiply by -1 to make it negative.
EDIT:
You can also use jQuery('input').data() to store the original number so you don't have to parse it again. (read more: http://api.jquery.com/data/ )