I know its good to use serverside validation for security, except this is just to get my head around validation.
My efforts so far have amounted to the following
function validateUser()
{
var x=document.forms["myForm"]["email"].value;
var y=document.forms["myForm"]["password"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
var uppercase = password.match(/[A-Z]/)
var lowercase = password.match(/[a-z]/g)
var number = password.match(/[0-9]/g)
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address or password");
return false;
}else{
alert("Valid Email Address and Password");
return true;
}
}
Basically, I need an alert box to pop up when the password doesn't have at least 1 lowercase, uppercase and a number. So far my code is just throwing an error when the email is in the wrong format. What do I add to the if statement to check the password characters?
Thanks in advance,
James
Few issues we have in your current implementation:
a. The error you're likely getting is that password is undefined.
Right now you're doing:
var y=document.forms["myForm"]["password"].value;
but you refer to it as "password" further on:
var uppercase = password.match(/[A-Z]/)
var lowercase = password.match(/[a-z]/g)
change the var y to:
var password=document.forms["myForm"]["password"].value;
b. To validate email, you should use a Regex such as:
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var isValidEmail = re.test(email);
c. To check for the password rules, you should just rely on the regular expressions you have in place already (and strip out the atpos, dotpos usage - that makes it much more complicated than it even needs to be).
Example:
var email='me#mailinator.com';
var password='test-P1assword';
var hasUpper = password.match(/[A-Z]/)
var hasLower = password.match(/[a-z]/g)
var hasNumber = password.match(/[0-9]/g)
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var isValidEmail = re.test(email);
if (isValidEmail && hasUpper && hasLower && hasNumber) {
alert("Valid Email Address and Password");
return true;
} else {
alert("Not a valid e-mail address or password");
return false;
}
JSFiddle example, complete with Regex to validate email AND password: http://jsfiddle.net/4hH3T/2/
The regex was taken from: Validate email address in JavaScript?
you can use regex to validate.
var reg=/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$/;
var isValid=reg.test(inputemail);
Related
I tried using the code below for a Full Name validation in a single input field with a space between the texts(a space between the first and second name). But for some reasons I couldn't make it work! Will you guys please kindly have a look at it?
This is the code:
<script>
lp.jQuery(function($) {
var ruleID = 'fullNameValid';
var field = 'full_name';
var message = 'Please enter a valid full name';
var rules = module.lp.form.data.validationRules[field];
$.validator.addMethod(ruleID, function(value, field) {
var valid = /^[a-zA-Z ]$/.test(value);
return valid || (!rules.required && !value);
}, message);
rules[ruleID] = true;
});
</script>
I have also tried using these options:
1.... var valid = /^[a-zA-Z ]$/.test(value);
2.... var valid = /^[a-zA-Z/s]$/.test(value);
3.... var valid = /^[a-zA-Z ]+$/.test(value);
4.... var valid = /^[a-zA-Z/s]+$/.test(value);
5.... var valid = /^([a-zA-Z ])$/.test(value));
6.... var valid = /^([a-zA-Z/s])$/.test(value));
7.... var valid = /^([a-zA-Z ]+)$/.test(value));
8.... var valid = /^([a-zA-Z/s]+)$/.test(value));
But the validation doesn't work! What am I doing wrong?
And this is my page: http://unbouncepages.com/pradaxa-one/
Thanks in advance.
var valid = /^[a-z]+ [a-z]+$/i
Maybe this regex can help you.
And you should trim the value at first.
console.log(/^([a-zA-Z]+ [a-zA-Z]+)$/.test("John Doe"));
console.log(/^([a-zA-Z]+ [a-zA-Z]+)$/.test("John Doe"));
console.log(/^([a-zA-Z]+ [a-zA-Z]+)$/.test("Jóhn Doe"));
console.log(/^([a-zA-Z]+ [a-zA-Z]+)$/.test("John Dö"));
It ONLY matches the alphabet in lower and uppercase. It does not validate Names with special characters as: "Jóhn Doe", "John Düstre"...
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've got an issue with the password validation.
That's my code:
function validatePassword(){
var password = document.getElementById("password").value;
var re = /^(?=.*[0-9])(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{6,16}$/;
if(!password.match(re)){
producePromt("The password is invalid","commandPasswordPrompt","red");
return false;
}
producePromt("Password is OK","commandPasswordPrompt","green");
return true;
}
It says that its only invalid, So I thought that its because of the regex.
I asked you if you can help with everything here.
Thanks a lot for helpers!
Try this
// At least eight numbers or/and letters of English or Hebrew language
^[a-zA-Z0-9\u0590-\u05FF]{8,}$
Or
// At least eight characters: one number, one uppercase, one lowercase English letter and one Hebrew letter
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\u0590-\u05FF]).{8,}$
Or
// At least eight characters: one number and one uppercase of lowercase English or Hebrew letter
^(?=.*[0-9])(?=.*[a-z|A-Z|\u0590-\u05FF]).{8,}$
Usage:
var p = /^(?=.*[0-9])(?=.*[a-z|A-Z|\u0590-\u05FF]).{8,}$/g;
var s = "שלוםWorld2";
if(!p.test(s)){
console.log("Invalid password!");
}
Regex Demo | jsBIn Demo
Maybe you could check it twice to make it easy.
For example:
var password = document.getElementById("password").value;
var re1 = /^a-zA-Z0-9!##$%^&*]{6,16}$/;
var re2 = /[0-9]/
var re3 = /[!##$%^&*]/
if(password.match(re1) && password.search(re2) >=0 && password.search(re3) >=0){
producePromt("The password is invalid","commandPasswordPrompt","red");
return false;
}
producePromt("Password is OK","commandPasswordPrompt","green");
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.
I have a form that accepts name, phone no. Currently, I have done validation for non empty fields. I want to add validation for name (alphabets) and phone no.(numbers).
My current code is given below. On submitting the form, I will be calling validateform() function:
function validateform()
{
var str= true;
document.getElementById("name").innerHTML="";
if(document.frm.name.value=="")
{
document.getElementById("name").innerHTML="Please enter Name";
str=false;
}
return str;
}
The value entered for name should be only alphabets. If not, I want to show the message "enter only alphabets". How should I do it?
/*mobile number of 10 digits */
var digit=10;
var pattern=/[0-9]{digit}/;
if(!pattern.match ( phoneno ) )
alert("not a valid number");
As noted in the comments, you can try something like this:
var rule = /^[a-zA-Z]*$/;
if(rule.test(document.frm.name.value)) {
// this contains only letters !
}
You could use regex to achive what you're trying to do.
function validatePhonenumber(value) {
var regexp = /^[0-9]+?$/;
return regexp.test(value);
}
function validateAlphabet(value) {
var regexp = /^[a-zA-Z ]*$/;
return regexp.test(value);
}
var alphaExp = /^[a-zA-Z]+$/;
if(!document.frm.name.match(alphaExp))
{
document.getElementById("name").innerHTML="Please enter only alphabets";
str=false;
}
var numExp = /^[0-9]+$/;
if(!document.frm.phone.match(numExp))
{
document.getElementById("phone").innerHTML="Please enter only numbers";
str=false;
}
With this you don't need to check for empty input. If you want to handle empty input separately, replace + with a * in the regexes.
function alphanumeric(inputtxt)
{
var letters = /^[0-9a-zA-Z]+$/;
if(inputtxt.value.match(letters))
{
alert('Your registration number have accepted : you can try another');
document.form1.text1.focus();
return true;
}
else
{
alert('Please input alphanumeric characters only');
return false;
}
}
See more here.