So I currently have this method for enforcing strong passwords:
$.validator.addMethod('goodPassword', function(value, element){
return this.optional(element) ||
value.length >= 6 &&
/\d/.test(value) &&
/[a-z]/i.test(value);
}, 'Your password sucks boy, you need at least 6 char and both number and char in that motherf.')
I want to create something similar for my usernames to limit them only to letters, numbers, dashes, underscores and periods. I can't seem to figure out how to go about it. I read about regex a little but still couldn't figure out how exactly I should go about my code.
This is what I currently have:
$.validator.addMethod('goodUsername', function(value, element)){
return this.optional(element) ||
value.length >= 4 // && or ||, not really sure what to put here
//something to check if entered data contains anything other than letters, numbers, dashes, underscores and periods
}, 'What kind of fkin username is that? You can only use letters, numbers, dashes, underscores and periods.')
Can someone show me the way please?
Here's the code that uses Javascript regex functionality
$.validator.addMethod('goodUsername', function(value, element)){
return this.optional(element) || value.match(/^[\w.-]{4,}$/m)
}, 'What kind of fkin username is that? You can only use letters, numbers, dashes, underscores and periods.')
As correctly noted by #rock321987, it'd still allow ...-... and other strange usernames.
you can use this function and set your custom illegal charters :
function validateUsername(fld) {
var error = "";
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (fld.value == "") {
fld.style.background = 'Yellow';
error = "You didn't enter a username.\n";
alert(error);
return false;
} else if ((fld.value.length < 5) || (fld.value.length > 15)) {
fld.style.background = 'Yellow';
error = "The username is the wrong length.\n";
alert(error);
return false;
} else if (illegalChars.test(fld.value)) {
fld.style.background = 'Yellow';
error = "The username contains illegal characters.\n";
alert(error);
return false;
} else {
fld.style.background = 'White';
}
return true;
}
I got this Regex to work and based off the jQuery Validator documentaion.
/^[a-z|A-Z]|\d|_|-|\./m
Here is how it look in the code. jQuery validator addMethod
$.validator.addMethod('goodUsername', function(value, element)){
return this.optional(element) || /^[a-z|A-Z]|\d|_|-|\./.test(value);
}, 'What kind of fkin username is that? You can only use letters, numbers, dashes, underscores and periods.');
I write use thie site to write my regular expressions regex 101
I ran it against these strings.
var str2 = 'uerhyeiufhsniufhsdJSHNAJDHJS09i304584305i4309SKA()*^&85$674&_-.dsf%#$fdfIIJ76..';
var str2 = 'dskfjdkaAHDNsfj34-2sds3432_-.*()$%#545#';
Related
In my application someone can submit text from another language. I'd like for only English alphanumeric strings to be entered. I've got this JavaScript function working but wondering if this is the best method for doing this?
var string = $('input[name=title]').val();
if((/\d/.test(string) || /[a-zA-Z]/.test(string)) === false) {
alert('Field has no Alphanumeric characters.');
fPass = false;
}
Even if some just enters 1 character I want that to be allowed, as long as it is a number or a character from one of the 26 letters in the English alphabet (case insensitive)
Without using a function here is what I've come up with
if((/[\da-z]/i.test(string)) === false) {
alert('Please use alphanumeric characters.')
}
You can combine your regex into one expression.
function hasAlphanumeric(str) {
return /\d|[A-z]/.test(str)
}
You can use
^[\da-z]+$
let allowAlphanumeric = (str) =>{
return /^[\da-z]+$/i.test(str)
}
console.log(allowAlphanumeric('$##'))
console.log(allowAlphanumeric(''))
console.log(allowAlphanumeric(' '))
console.log(allowAlphanumeric('abchbchdb12e44'))
I'm trying to solve a password checker challenge and I've got to a stage where 1 string is matching for two expressions.
Rules:
return 'too short' for any string that is less than 6 characters
return 'okay' if the string is less than 12 characters, features one or more underscores, or a number, or with a mix of uppercase/lowercase letters
var str = 'aBB33'
var lessthansixRegex = new RegExp(/^(?=.*?[a-z])(?=.*?[A-Z])|(?=.*?\d{1}){0,6}$/);
var okayRegex = new RegExp(/(?=.*?[a-z])(?=.*?[A-Z])|(?=.*?\d{1})|(?=.*?[_]{1})/);
if (okayRegex.test(str) && str.length < 12) {
return 'okay';
} else if (tooshortRegex.test(str) && str.length < 6) {
return 'too short';
}
Is there a way to check this or are the paramaters of the challenge messed up.
One solution you might easily spot is the lack of '' however the 'okay' regex must have that parameter as an or '|' because there are other strings than need to match it that also don't include ''.
Feel free to let me know if you spot any other bugs.
Thanks a lot!
I think you've overcomplicated things here, why not just check the string lengths rather than write a regex for it? Also I think your regex could be simpler:
var str = 'aBB33';
var okayRegex = /[_\d]|[A-Z]+.*[a-z]+|[a-z]+.*[A-Z]+/;
if (str.length < 6 || str.length > 11) {
return 'password must be between 6 & 11 characters';
} else if (okayRegex.test(str)) {
return 'ok';
} else {
return 'invalid password';
}
Seeing as this is about the regex let me explain what's happening:
[_\d] // match any underscore or digit (number)
| // or (checks whether what's before or after is true)
[A-Z]+.*[a-z]+ // check for at least one A-Z followed by any gap
// of characters followed by at least one a-z
| // or
[a-z]+.*[A-Z]+ // reverse of last check (lower then upper)
Hope that helps!
Your regex seems too complicated. You can reach your solution by testing against each individual regex and provide a specific error message based on each condition by doing something like this
var containsNumber = new RegExp('\d');
var containsUnderscore = new RegExp('[_]');
var containsUpperCase = new RegExp('[A-Z]');
var containslowerCase = new RegExp('[a-z]');
if (str.length < 6 || str.length > 11) {
return 'password must be between 6 & 11 characters';
} else if (!containsNumber.test(str)) {
return 'password must contain a number';
}else if (!containsUnderscore.test(str)) {
return 'password must contain underscore';
}else if (!containsUpperCase.test(str)) {
return 'password must contain upper case character';
}else if (!containslowerCase.test(str)) {
return 'password must contain lower case character';
}
Trying to validate my form and set up a variable for invalid characters, but I'm having trouble getting them recognized because they're just a bunch of symbols? -
function validation(){
var Name =
document.getElementById("name").value;
var Email = document.getElementByID("email").value;
var invalidSymbol = /[\~\`\!\#\$\%\^\&\*\(\)\-\+\{\}\:\\\;\"\'\<\>\?\,\]/;
if Name == ""{
alert("Please enter your name");
document.getElementById("Name").focus();
return false;
}else if (Email == "" | | Email.indexOf("#")<1 || Email.lastIndexOf("#")+2 || Email.lastIndexOf(".")+2>=Email.indexOf("#").length || Email.match(invalidSymbol)){
alert ("Please enter a valid e-mail address");
document.getElementById("email").focus();
return false;
}else{
return true;
}
}
var desired = stringToReplace.replace(/[^\w\s]/gi, '')
As was mentioned in the comments it's easier to do this as a whitelist
- replace the characters which aren't in your safelist.
The caret (^) character is the negation of the set [...], gi say
global and case-insensitive (the latter is a bit redundant but I
wanted to mention it) and the safelist in this example is digits, word
characters, underscores (\w) and whitespace (\s).
As stated here:
javascript regexp remove all special characters
by
annakata
I want to make a regex validation using hexadecimal metacharacters. the reason i decided to go this way it because i need only the greek language to work.
from http://www.unicode.org/Public/UNIDATA/Blocks.txt i see that i need to use characters from 1F00 to 1FFF. however i cannot find what is going wrong.
here's what i've done so far:
document.querySelector("#register input[name='first_name']").onblur =
function(){
/*RegEx about name*/
var str = /[\u1F00-\u1FFF]/g;
var name = document.querySelector("#registerinput[name='first_name']").value;
if (name == null || name == ""){
alert("First name must be filled out!");
}
else if(!name.match(str)){
alert("Name must contain (greek)letters only!");
}
};
The range you are using is Greek extended. You want the range from 0370 to 03ff. From the page you quoted:
0370..03FF; Greek and Coptic
1F00..1FFF; Greek Extended
function is_greek(name){
var greek = /[\u0370-\u03ff]/;
return greek.test(name);
}
> is_greek("α")
< true
I have textbox called goalName. In goalName I want to disallow special characters and numbers. I am currently trying the following:
var goalNameValidation = /^[_\W\s]*$/;
if (goalName == "" || goalNameValidation.test(goalName) == true) {
//Give Error
error = true;
}
This only limits special characters, and not numbers. How would I go about restricting both?
I can use jQuery for this solution if that is helpful, however vanilla JavaScript would suffice.
It is probably easier (and more intuitive) to write a regex that matches what you WANT to allow.
var goalNameValidation = /^[A-Za-z]+$/;
if (goalName == "" || goalNameValidation.test(goalName) == false) {
//Give Error
error = true;
}
This way, you can look at it, and see more easily what characters are allowed/not allowed.
Change the regexp to:
var goalNameValidation = /^[^a-z]*$/i;