How to validate a password in javascript - javascript

This is the code I wrote, it returns the alert every time even if the password is within the range(4-12).
function PasswordCheck() {
var str = document.getElementById("Password");
if (str > 4 && str < 12) {
return true;
} else {
alert("invalid password, your password needs to have 4-12 letters");
return false;
}
}

You need to retrieve the text in your element with value.
Then you want to check the length of your string with the Ā length property of the str string.
function PasswordCheck() {
var str = document.getElementById("Password").value;
if (str.length > 4 && str.length < 12) {
return true;
} else {
alert("invalid password, your password needs to have 4-12 letters");
return false;
}
}
This is because getElementById returns an Element object and not the value directly.

Related

How to make usernames banned on a website

How can I find out if a text input is a certain text?
I tried this
<script>
var b = document.getElementById('button')
var u = document.getElementById('username')
var p = document.getElementById('password')
var bannedUsers = ["user1012"];
b.onclick = function() {
if(u.value.length <= 20 && p.value.length >= 6 && u.value.length >= 3 && !u.value === bannedUsers) {
location.href = "";
};
if(u.value.length > 20) {
return alert('Username needs to be below 20 characters.')
} else if(u.value.length < 3) {
return alert('Username needs to be above 2 characters')
}
if(p.value.length < 6) {
return alert('Password needs to be over 6 characters.')
}
if(u.value === bannedUsers) {
return alert('That username is banned.')
}
}
</script>
But it ended up just taking me to the page instead of saying "This username is banned"
You need to use the includes method.
bannedUsers.includes(u.value)
what you're doing right now is checking if the string is the array bannedUsers, translating to this: 'user1012' === '[object Object]'
You can use the Array.prototype.includes method to test if a given value is in an array. includes will return a boolean true or false.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
if (bannedUsers.includes(u.value) {
return alert('That username is banned.')
}

validate password length after user leave password field

I want to check if the password length is at least 8 characters or not, when the user leaves the password field or press tab key.
How can i do this?
My code for password is shown below.
<input type="password" name="password" id="pass1" placeholder="password"/>
Use the jquery blur method for this.
$('#pass1').on('blur', function(){
if(this.value.length < 8){ // checks the password value length
alert('You have entered less than 8 characters for password');
$(this).focus(); // focuses the current field.
return false; // stops the execution.
}
});
Fiddle for Demo
You can use javascript onchange event as below
and script code callfunction() as
function callfunction()
{
var textBox = document.getElementById("pass1");
var textLength = textBox.value.length;
if(textBox.value=='' || textLength<=8)
{
alert('Please enter correct password');
}
}
try this:
$('#pass1').on('blur', function(){
if($(this).val().length > 8){
alert('safe!');
}
});
here is an example: http://jsfiddle.net/ACK2f/
Password validation can use several rules, I used a service but the code inside the function can be reusable:
_validatePassword = function (validateUserNameRules, Model)
{
//bolean parameter validateUserNameRules -> true/false
//this method recive a model like this:
//Model.userName -> string
//Model.password -> string
//Model.password2 -> String
var validationResult = {
ResultId: 1, //1 success
Message: "Password is correct."
};
if (validateUserNameRules && Model.userName == "") {
validationResult.ResultId = 2;
validationResult.Message = "Error: User name cannot be blank.";
return (validationResult);
}
var re = /^\w+$/;
if (validateUserNameRules && !re.test(Model.userName)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: Username must contain only letters, numbers and underscores.";
return (validationResult);
}
if (Model.password != "" && Model.password == Model.password2) {
if (Model.password.length < 6) {
validationResult.ResultId = 2;
validationResult.Message = "Error: Password must contain at least six characters.";
return (validationResult);
}
if (validateUserNameRules && Model.password == Model.userName) {
validationResult.ResultId = 2;
validationResult.Message = "Error: Password must be different from the Account Name.";
return (validationResult);
}
re = /[0-9]/;
if (!re.test(Model.password)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: password must contain at least one number (0-9).";
return (validationResult);
}
re = /[a-z]/;
if (!re.test(Model.password)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: password must contain at least one lowercase letter (a-z).";
return (validationResult);
}
re = /[A-Z]/;
if (!re.test(Model.password)) {
validationResult.ResultId = 2;
validationResult.Message = "Error: password must contain at least one uppercase letter (A-Z).";
return (validationResult);
}
} else {
validationResult.ResultId = 2;
validationResult.Message = "Error: Please check that you've entered and confirmed your password.";
return (validationResult);
}
return (validationResult); //success password validation!!
};

How to validate a url and a text?

In one of my textbox i need to enter only multiple url or multiple text at a time,not both.
So while i use the regular expression given below the domain name "google.com" will satisfy the condition of text.But i need to return false for this type of entry.Can anyone please suggest an idea?
jQuery.validator.addMethod("newway", function(value, element) {
var testarray = ['.....'];
var url_count = 0;
var text_count = 0;
for(var k in testarray){
if(/^(http:\/\/|https:\/\/)?((([\w-]+\.)+[\w-]+)|localhost)(\/[\w- .\/?%&=]*)?/i.test(testarray[k]))
{
console.log("url");
url_count++;
}
else{
if(/^[a-zA-Z+,:;%()]+$/.test(testarray[k])){
console.log("text");
text_count++;
}
}
}
if((url_count==0 && text_count > 0) || (url_count >0 && text_count == 0)){
if((url_count==testarray.length) || (text_count==testarray.length)){
return true
}
else{
return false
}
}else{
return false
}
}, "Please enter url or text");

How to validate multiple fields at the same time using JQuery

I have created a form that validates using JQuery and JavaScript. The only problem is, would be that it validates one field at a time. So the user has to correct the first field first and then press submit again to see if the next field is valid.
What I would like to to do, is have the JQuery validate the whole form after pressing submit and show all the applicable error messages.
Here is My JS:
function validateUserName()
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
return false;
}
else if (uLength < 4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
return false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
return false;
}
else
{
return true;
}
}
function validatePassword()
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
$("#ErrorPassword1").text("You left the password field empty");
return false;
}
else if (pLength < 6 || pLength > 20)
{
$("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
return false;
}
else if (p != cP)
{
$("#ErrorPassword1").text("Th passwords do not match!");
return false;
}
else
{
return true;
}
}
function validateEmail()
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/;
var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/;
if (eLength == "" || eLength == null)
{
$("#ErrorEmail").text("You left the email field blank!");
return false;
}
else if (e.match(illegalChars))
{
$("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
return false;
}
else
{
return true;
}
}
function validateFirstName()
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if (fLength > 20)
{
$("#ErrorFname").text("First Name has a max of 20 characters");
return false;
}
else if (illegalChars.test(f))
{
$("#ErrorFname").text("Numbers,letter and underscores in first name only");
return false;
}
else
{
return true;
}
}
function validateLastName()
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if (lLength > 100)
{
$("#ErrorLname").text("Last Name has a max of 100 characters");
return false;
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only");
return false;
}
else
{
return true;
}
}
function validateForm()
{
valid = true;
//call username function
valid = valid && validateUserName();
//call password function
valid = valid && validatePassword();
//call email function
valid = valid && validateEmail();
//call first name function
valid = valid && validateFirstName();
//call first name function
valid = valid && validateLastName();
return valid;
}
And here is my submit form code:
$('#your-form').submit(validateForm);
Instead of returning true or false return a string containing the error and an empty string if no error was found.
Then validateForm could be something like
function validateForm()
{
error = "";
//call username function
error += "\n"+validateUserName();
//call password function
error += "\n"+validatePassword();
...
if(error === ""){
return true;
}
$("#ErrorLname").text(error);
return false;
}
Working Fiddle
var validate;
function validateUserName()
{
validate = true;
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
$("#ErrorUser").text("You Left the Username field Emptyyy");
validate = false;
}
else if (uLength <4 || uLength > 11)
{
$("#ErrorUser").text("The Username must be between 4 and 11 characters");
validate = false;
}
else if (illegalChars.test(u))
{
$("#ErrorUser").text("The Username contains illegal charectors men!");
validate = false;
}
}
function validatePassword()
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
$("#ErrorPassword1").text("You left the password field empty");
validate = false;
}
else if (pLength < 6 || pLength > 20)
{
$("#ErrorPassword1").text("Your password must be between 6 and 20 characters in length");
validate = false;
}
else if (p != cP)
{
$("#ErrorPassword1").text("Th passwords do not match!");
validate = false;
}
}
function validateEmail()
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (eLength == "" || eLength == null)
{
$("#ErrorEmail").text("You left the email field blank!");
validate = false;
}
else if (e.match(illegalChars))
{
$("#ErrorEmail").text("ILEGAL CHARECTORS DETECTED EXTERMINATE");
validate = false;
}
}
function validateFirstName()
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if(fLength > 20)
{
$("#ErrorFname").text("First Name has a max of 20 characters");
validate = false;
}
else if (illegalChars.test(f))
{
$("#ErrorFname").text("Numbers,letter and underscores in first name only");
validate = false;
}
}
function validateLastName()
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if(lLength > 100)
{
$("#ErrorLname").text("Last Name has a max of 100 characters");
validate = false;
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only");
validate = false;
}
}
function validateForm()
{
validateUserName();
validatePassword();
validateEmail();
validateFirstName();
validateLastName();
return validate;
}
You need to access all the fields and check if the field is valid r not. If the field is valid skip it, otherwise put the field in an array. When all the fields have been checked, then display the error fields from the array all at one time.

JavaScript Form onkeyup Validation Errors

Not getting any errors in Aptana, so something I'm doing probably doesn't make sense. Basically, I am getting the value from a form and checking it against a regex. If the new checked variable isn't empty then I output to a different div that it is valid, and that it is not valid if the variable is empty.
<script type="text/javascript">
var age_regex=/(1[8-9]|2[0-9]|3[0-5])/;
var error_box= document.getElementById('error_box');
function checkAge(x){
var age = document.getElementById(x).value;
var checked_age = test.age_regex(age);
if (checked_age.value != "")
error_box.innerHTML = "Correct!";
else {
error_box.innerHTML = "Incorrect!";
}
}
</script>
Why regex for age ? How about this :
function checkAge(str) {
if(parseInt(str, 10) != str) {
return false;
}
if(parseInt(str, 10) < 18 || parseInt(str, 10) > 35)
{
return false;
}
}

Categories