Validating name in visual studio code - javascript

var userName = input.question('Please enter your name: '); //Asking User to enter their Name.
while (userName.includes('.')) {
console.log ("Invalid Name!");
var userName = input.question('Please enter your name: '); //Asking User to enter their Name.
}
Above code will ask the user his/her name and store it in "userName". Then it will validate using .includes to check unwanted characters and numbers.
I want to validate if userName has numbers or unwanted characters such as "?/.,;'[]{}|&^%#" etc. I have tried using .includes and validate if a name has "." However, I'm not sure how to go about from there to validate the rest.
After the while checks that it contains the unwanted characters, it will re-prompt the user to enter a new name and it will check again until it returns false.
Is there a solution to this?

You can use REGEX to search for non-alphabetic or space characters in the string:
userName.search(/^[a-zA-Z\s]+$/)
The response will be 0 or -1. 0 means that no characters except A-Z, a-z and space were found, -1 means the contrary.
Edit: I found similar question with more detailed answers here.

let chars = /[$&+,:;=?##|'<>.^*()%!-]/g;
chars.test(UserName)
Use Regular expressions ( Regex )
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Related

Not able to match the RegExp in JavaScript even it is matching in QuickRex

Not able to match the regular expression in my JavaScript code which I have written for form validation.
I wanted to validate my form field which is password using RegExp [[0-9]{0,8}[a-z]{0,8}[A-Z]{1,8}#]
My Validations on password is
- Should contain 10 characters including digit
- At least one uppercase letter should be there
- Only # should be used as special character
But the same is working with [0-9a-zA-Z#]{10} but not with [[0-9]{0,8}[a-z]{0,8}[A-Z]{1,8}#]
var regexpassword=/[[0-9]{0,8}[a-z]{0,8}[A-Z]{1,8}#]/
if(!regexpassword.test(password.value)){
alert("Enter valid password")
password.focus();
return false
}
NOTE: The password that I have entered is Welcome#67
It should not give the alert as "Enter valid password"
Best I can tell, the regex you provided, is matching exactly 1 character. the [] operator indicates "any of what is inside". But the only place you are indicating "multiple times" is the [A-Z]{1,8}. Also, as #Pointy mentioned, I don't think you can nest square brackets. Even if you can, it is somewhat redundant.
Your regex is being interpreted as follows:
1. Look for [ or the numbers 0 through 9 between 0 and 8 times in a row
2. Followed precisely by the lowercase letters a through z between 0 and 8 times in a row
3. Followed precisely by the uppercase letters A through Z between 1 and 8 times in a row
4. Followed precisely by a single #
5. Followed precisely by a single ]
This leads to matching strings like (but not limited to):
[A#]
0A#]
9aaaaaaaZ#]
[0123456abcdefghABCDEFGH#]
[[[[[[[[Q#]
[[[[[[[[azazazazAZAZAZAZ#]
but it will not match Welcome#67.
Is there a way to write a regex that will validate a password with your requirements?
Possibly.
Should you use a single regex to validate your password?
Probably not as the necessary complexity of that regex would make it impractical to maintain when your password requirements change.
Is there a practical, maintainable way to validate passwords?
Certainly! Use multiple regexes to validate the required parts of the password.
Then determine if the needed parts are present and make sure the length is acceptable.
Example:
var hasOnlyValidCharacters = /^[0-9a-zA-Z#]+$/gm.test(password.value);
var hasDigits = /[0-9]+/gm.test(password.value);
var hasUpper = /[A-Z]+/gm.test(password.value);
var hasLower = /[a-z]+/gm.test(password.value);
var hasAtSign = /[#]+/gm.test(password.value); // Technically could be /#+/gm.test(...), but I tend to use character classes every time I'm looking for specific characters.
var isValidPassword = (
password.value.length === 10 // Should contain 10 characters
&& hasOnlyValidCharacters
&& hasDigits // including digit
&& hasUpper // At least one uppercase letter should be there
// && hasLower // Uncomment to require at least one lowercase letter
// && hasAtSign // Uncomment to require at least one #
);
if (!isValidPassword) {
alert("Enter valid password")
password.focus();
return false
}
The [untested code] above should do the trick, and following the patterns established in it, you should be able to easily change your password requirements on a whim.

Regex to match only certain characters or strings and only one instance of each?

I feel like I know just enough about Regexes to get stuck. That said, I have an input field which will allow users to enter their currency symbol. I'm only wanting to allow said currency symbol and disallow anything else from being entered into that field. Some countries don't actually have a single symbol, but are just two or three characters, e.g., "Kr" for Krona. So the field has a max length of 3. Given it needs a max length of three to accommodate some currencies, I also don't want to allow three dollar signs to be entered, e.g., "$$$". I would only want to allow one single dollar, pound, euro, etc. sign.
Here's my basic code for allowing only these symbos in the input:
$('#id_currency_symbol').on('input',function (){
var value = $(this).val().toString();
newvalue = value.replace(/[^$£€¥₣₩₩¥₽₺₹Rkr]+/g,'');
$(this).val(newvalue);
});
This works for only allowing these symbols/letters, but like I said above, I don't want to allow users to enter more than a single instance of some symbols, i.e. dollar sign ($). In addition, I want to match exact strings for cases where the "symbol" is actually just two or three characters. In the case of Krona, the "symbol" is Kr. Given the above, users could in theory enter "rK" and it would be perfectly valid according to the regex, but I would ONLY want to allow the exact match of "Kr." Is that possible?
Thanks
I would suggest to forget regex, and go for O(1) algos,
var allowedCurrencyCodes = {
"$":true,
"¢":true,
"£":true,
"INR":true,
"Kr":true,
.....,
.....,
.....
}
$(this).val(allowedCurrencyCodes[$(this).val()]?$(this).val():"");
you need to perform the check at blur event or when user has entered at least 3 chars, else it becomes buggy as it will keep on wiping the data right after first char.
if you want to keep check real time i.e. responsive when user is typing in, then you need to change the structure of allowedCurrencyCodes and convert it to nested object for multi-char currency codes, e.g $,£ would be exactly same but INR or Kr will be defined like
"I":{
"N":{
"R":true
}
},
"K":{
"r":true
}
and minor change in fetch logic will be applied, where you will capture input and split it in array and then dip in allowedCurrencyCodes based on input chars, like
allowedCurrencyCodes[inputChar[0]][inputChar[1]]
or
allowedCurrencyCodes[inputChar[0]][inputChar[1]][inputChar[2]]
You may find the first occurrence of a currency symbol or acronym using a regex and then replace the whole input with the matched string. Single character currencies can be listed in [...] and any longer string may be added by alternation:
var checkInput = function(input) {
var regex = /[$£€¥₣₩₩¥₽₺₹]|kr/i;
input = regex.exec(input);
return input == null ? "" : input[0];
}
console.log(checkInput("lkjahfkdshfjsdf Kr asdasda"));
console.log(checkInput("kr"));
console.log(checkInput("rk"));
console.log(checkInput("$$$"));
console.log(checkInput("₣₩₩"));
console.log(checkInput("ABC"));
For completeness:
The "Regex to match only certain characters or strings and only one instance of each":
^(?:[$£€¥₣₩₩¥₽₺₹]|kr)$
Demo: https://regex101.com/r/w9p9d9/1
Regex to strip off anything but "certain characters or strings" and these characters too if they appear more than once (for use within newvalue = value.replace(...,'');):
^(?=.*?([$£€¥₣₩₩¥₽₺₹]|kr)|).*
Demo: https://regex101.com/r/qocsv5/1

check input fields with javascript

i am using the following code to check if user doesnt input special characters in name
var regex = /^[a-zA-Z ]{2,50}$/;//check for only letters
var ctrl = document.getElementById('input1');//given name field
if(!regex.test(ctrl.value))
{
alert('Ensure field Name contains only letters[A-Z]');
return;
}
can someone please help to change regex so client can also enter JUST one (')(IF NEEDED) e.g O'Daniel.
also for phone no field limit user with only one +
Thanks in advance.
You don't have to cram all the logic into a single regexp. To check for apostrophes, simply do a separate check:
var apostrophes = ctrl.value.match(/'/g);
return !apostrophes || apostrophes.length < = 1;
Use the same logic to check for no more than one + in the phone number.

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.

Extract proper username from a string with regex in js

I want to extract a username from a string that user has typed into input. The thing is that I don't want just simply validate username, but I want to show for user what will be the final username even if user types any non-allowed characters.
So for example if user types in something like &%$User)(Nam-e it will show usernam-e
there is similar question with answer Regular expression to validate username, but somehow it gives me an error of Invalid group on node.js when I try to use it with a match or exec functions.
Anyway, most of the examples online only validates the username against regex, but not actually provides the outcome of the appropriate username.
Rules are following:
Only contains alphanumeric characters, underscore, dash and dot.
Underscore, dash and dot can't be at the end or start of a username
(e.g _username / username_).
Underscore, dash and dot can't be next to each other (e.g
user_-.name).
Underscore, dash or dot can't be used multiple times in a row (e.g
user__name).
So far I was only capable to do something similar with using replace function number of times
value.replace(/[^\w-]*/g,'').replace(/^[^a-z]*/,'').replace(/-{2,}/g,'-').replace(/_{2,}/g,'_');
But this doesn't look like an efficient code, especially that I would actually need to add even more replace functions to extract appropriate username.
Any ideas how to achieve that?
Assumes that you want the name displayed in lower-case, as in your example:
function user( n ) {
var name = n.replace( /^[^a-z]+|[^a-z\d_\-.]|[_\-.](?![a-z\d])/gi, '' );
if ( n != name ) {
console.log( 'Username invalid' );
}
return name.toLowerCase();
}
user('&%$User)(Nam-e'); // Username invalid, usernam-e
user('_Giedrius_one_'); // Username invalid, giedrius_one
user('Giedrius--one'); // Username invalid, giedrius-one
user('Giedrius-one'); // giedrius-one
user('/.bob_/'); // Username invalid, bob

Categories

Resources