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
Related
I'm trying to do a validation including these requires:
Allow to insert a name with space between , example: "Nicolas Tesla"
Not allow to insert spaces or numbers , example: " " or "12354"
I have this function but i don't know if i'm doing right:
function ValidName(){
var regex = /^[a-zA-Z]$/;
var name = $("#txtNome").val();
if(name == ""){
alert("Please, type your name.");
name.focus();
return false;
}
else if(name =! name.regex){
alert("Please, type your name.");
name.focus();
return false;
}
}
The first "if" is working , if i don't type anything then alert comes out , but the second one isn't and i don't know if i'm doing right , in fact i don't know what i'ma doing.
First of all, modify your regex so that it accepts strings with at least one character separated with one space with another set of one or more characters:
var regex = /^[a-zA-Z]+(\s[a-zA-Z]+)?$/;
That will save you the first "if" statement.
Then, to check if your regex match, you should use RegExp.prototype.test
your code would then look like
function ValidName(){
var regex = /^[a-zA-Z]+(\s[a-zA-Z]+)?$/;
var $name = $("#txtNome");
if(!regex.test($name.val())){
alert("Please, type your name.");
$name.focus();
return false;
}
return true;
}
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#';
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 am using a regex to validate an email address in JavaScript.
The regex is pretty simple. It checks three things: 1)'#' , 2)'.' ('dot' as in something#gmail.com), and 3) 'a-z' in an email address. If all three return true, email address is valid (according to my validation, atleast)
Here is the code:
function checkemail(){
var e = document.getElementById("email").value;
if((e.match(/#/g)==null)||(e.match(/[a-z]/ig)==null)||(e.match(/./g)==null)){
//display error message
}
}
My question is:
(e.match(/./g)==null); //returns false even though there are no dots in the string e
returns false even when there are no dots in string.
For example:
("thisIsMyEmail".match(/./ig))==null //returns false
Why does it return false when it should be true?
/./g (or /./ig) will match any string that as at least one character in it. . is special in regular expressions, it means "any character here."
For an actual dot, escape it with a backslash: /\./g.
First off, you don't need to check if the string is null. Simply use this:
var email = "Godisgood#gmail.com";
if (email.match(/^\S+\#\S+\.\S+$/i)){
alert("Email address passed validation.");
}
you have to escape the .
The unescaped period means matches any character.
Meaning having a string "abc" using your expression would result in an array containing the characters 'a', 'b', and 'c'.
In your snippet the correct answer is
(e.match(/\./g)==null);
This should result to what you're expecting
Try this
(e.match(/\./g)==null);
. matches any character so needs escaping /\./g
I know you have already got the answer.
But I just want to give an advice.
My advice is - don't use the javascript code to validate any email address; because as per your code, #domain., #domain.com these all are also valid email, but everybody knows these are not a valid email address.
So use the below code:
let email = $(this).val();
var positionOfAt = email.indexOf("#");
var positionOfDot = email.lastIndexOf(".");
if(email.search("#") == -1 || //if '#' is not present
email.search(" ") >= 1 || //if blank space is present
email.search(".") == -1 || //if "." is not present
positionOfAt < 1 || //if there is no character before "#", at least one character should be present before "#"
positionOfDot - positionOfAt <= 2 || //between '#' and '.', if there is not at least two character
email.length - positionOfDot <= 2) //if after '.' there is not at least two character)
{
console.log("Invalid email id")
}
else
{
console.log("Valid email id")
}
So far I have this:
function validateForm() {
var str=document.forms["myForm"]["email"].value;
var atpos=str.indexOf("#");
var dotpos=str.lastIndexOf(".com");
if (atpos>0 || dotpos<atpos+2 || dotpos+2>=str.length)
{
alert("Incorrect e-mail address");
return false;
}
}
How can I include the '#' to be shown ONCE in the character string? (So an email can't be validated as ##).
I also would appreciate it if it were anything but the regex method.
If you don't want use regex, you can split a string by an occurrence.
var email = "foor#bar.com";
if((email.split('#').length != 2) {
// it's not an email address
}
else {
// it is an email address
}
A nice hack is to check if the first # is also the last #.
if(str.indexOf('#') != -1 && str.indexOf('#') == str.lastIndexOf('#')){
// email is valid
}
Check this buddy
function validateForm()
{
var x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
The best way to validate the email address is through regular expressions:
/^\w+([\-+\.']\w+)*#\w+([\-\.]\w+)*\.\w+([\-\.]\w+)*$/
If you do not know regular expressions, I suggest that you learn them right away, since they are a pretty powerful and useful feature when dealing with and validating string content.