Password validation using javaScript , not working correctly - javascript

this is my email address validation using JavaScript, I have only two conditions that work, the one with the special character is not working.
Only the third is tested on the email address, the first two are on the password.
Please help me.
<script type = "text/javascript">
function validateEmail(form) {
var tr = /[A-Za-z0-9]{8,}/
var tr2 = /\S+#\S+\.\S+/
var tr3 = /[A-Za-z0-9]+[a-zA-Z0-9.!$+/?_]/
if (!(tr.test(form.password.value))){
alert("The passowrd length must be more than 8 letters.")
return false;
}
else if (!(tr3.test(form.password.value))){
alert("Enter a special character.")
return false;
}
else if (!(tr2.test(form.email.value))){
alert("Enter a valid email.")
return false;
}
else{
alert("signed in successfully")
window,open("HomePage.html")
return true
}
}
</script>

Just change regex to this.
const form = {
password: {
value: 'buffaloBill3##$',
},
email: {
value: 'hannibal#lecter.com'
}
};
function validateEmail(form) {
var tr = /[A-Za-z0-9]{8,}/
var tr2 = /\S+#\S+\.\S+/
var tr3 = /^(?=.*[!##$%^&*])[a-zA-Z0-9!##$%^&*]{0,}$/;
if (!(tr.test(form.password.value))) {
alert("The passowrd length must be more than 8 letters.")
return false;
} else if (!(tr3.test(form.password.value))) {
alert("Enter a special character.")
return false;
} else if (!(tr2.test(form.email.value))) {
alert("Enter a valid email.")
return false;
} else {
alert("signed in successfully")
window, open("HomePage.html")
return true
}
}
validateEmail(form);

Related

e.preventDefault() not letting me submit my form

I wrote some Javascript to validate a form. However, if the form fields pass all validations, the form never submits! Is my code somehow incorrectly preventing the form from being able to submit? If I delete all of the Javascript and use browser's built-in validation then form executes fine and user is added to the database.
const form = document.getElementById('form');
const first_name = document.getElementById('first_name');
const last_name = document.getElementById('last_name');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
// Show input error message
function showError(input, message) {
input.className = 'form-control is-invalid';
const small = input.parentElement.querySelector('small');
small.className = 'invalid-feedback';
small.innerText = message;
}
// Show success outline
function showSuccess(input, message) {
input.className = 'form-control is-valid';
const small = input.parentElement.querySelector('small');
small.className = 'valid-feedback';
small.innerText = message;
}
function checkRequired(inputArray) {
inputArray.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
return false;
} else {
showSuccess(input, "Looks Good!");
return true;
}
});
}
// Check email is valid
function checkEmail(input) {
const 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,}))$/;
if (re.test(input.value.trim())) {
showSuccess(input, 'Looks Good!');
return true;
} else {
showError(input, 'Email is not valid');
return false;
}
}
// Check input length
function checkLength(input, min, max) {
if (input.value.length < min) {
showError(
input,
`${getFieldName(input)} must be at least ${min} characters`
);
return false;
} else if (input.value.length > max) {
showError(
input,
`${getFieldName(input)} must be less than ${max} characters`
);
return false;
} else {
showSuccess(input, 'Looks Good!');
return true;
}
}
// Check passwords match
function checkPasswordsMatch(input1, input2) {
if (input1.value !== input2.value) {
showError(input2, 'Passwords do not match');
return false;
}
return true;
}
// Get fieldname
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
// Event listeners
form.addEventListener('submit', function(e) {
if (!checkRequired([first_name, last_name, username, email, password, password2])) {
e.preventDefault();
}
if (!checkLength(username, 3, 15)) {
e.preventDefault();
}
if (!checkLength(password, 6, 25)) {
e.preventDefault();
}
if (!checkEmail(email)) {
e.preventDefault();
}
if (!checkPasswordsMatch(password, password2)) {
e.preventDefault();
}
});
Your checkRequired function never returns anything at the moment:
function checkRequired(inputArray) {
inputArray.forEach(function (input) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
return false;
} else {
showSuccess(input, "Looks Good!");
return true;
}
});
}
You're returning inside the callback, but the callback ignores its return value (and you still wouldn't want to return true inside the loop, you'd only want to return true after all iterations have finished)
To find the first invalid input, use .find:
function checkRequired(inputArray) {
const invalidInput = inputArray.find(input => input.value.trim() === '');
if (invalidInput) {
showError(input, `${getFieldName(invalidInput)} is required`);
return false;
}
return true;
}
If you want to call showError for every invalid input, then:
function checkRequired(inputArray) {
let valid = true;
for (const input of inputArray) {
if (input.value.trim() === '') {
valid = false;
showError(input, `${getFieldName(input)} is required`);
}
}
return valid;
}
You are not returning anything from checkRequired so it's value will always be false. Although there should be no performance problems, you might be better off using a for loops so that you can break early.
function checkRequired(inputArray) {
for (let input of inputArray) {
if (input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
return false;
}
}
return true;
}

Creating a pattern for a number which must be prefixed by 3 letters eg (IKA111111)

function validatetest(e)
{
debugger;
e.preventDefault();
// Declare all the variables here
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var title = document.getElementById("title").value;
var healthNumber = document.getElementById("healthNumber").value);
var email = document.getElementById("email").value;
var telephoneNumber = parseInt(document.getElementById("telephoneNumber").value);
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
var validText = /^[a-zA-Z]*$/;
var validLastText = /^[a-zA-Z-]*$/;
var validEmail = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]{2,6}$/;
//var n = healthNumber.startsWith("ZHA");
if(firstName!="" && lastName!= "" && title!="" && email !="")
{
if(email.match(validEmail))
{
if(!isNaN(telephoneNumber) && telephoneNumber >= 11111111111 && telephoneNumber <= 99999999999)
{
if(firstName.match(validText) && firstName.length >1)
{
if(lastName.match(validLastText) && lastName.length> 1)
{
if(healthNumber.match(validHealth))
{
alert("All information is Validated");
return true;
}
else
{
alert("error error");
return false;
}
}
else
{
document.getElementById("error4").innerHTML="letters and hypen only";
return false;
}
}
else
{
document.getElementById("error").innerHTML="letters only and more then one character";
return false;
}
}
else
{
document.getElementById("error2").innerHTML="Telephone number must be 11 num digits long";
}
}
else
{
document.getElementById("error3").innerHTML="email is not a valid format ";
return false;
}
}
else
{
alert("All fields must be entered except telephone Number ");
return false;
}
}
i am trying to create a validation process by using a pattern for a user inputted healthnumber so that it validates whether 3 letters are entered followed by 6 numbers via user input. (MIC123456 is example so MIC always has to been entered , those specific letters)
Not sure if my technique is correct by using a pattern stored in the ValidHeath variable as you can i have used this idea for my email validation etc .
You have an extra + in your regex, make it
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
Demo
var isMatch = !!"IKA111111".match(/^[A-Z]{3}[0-9]{6}$/);
isMatch ? console.log( "Matching" ) : console.log( "Not Matching" );

Javascript password validation skip if fields are empty

This works great, but I need it to do is also ignore it if the password field is left blank.
I want the user to be able to update their information without having to change their password. So if they leave the password fields blank, their password remain the same.
document.addEventListener("DOMContentLoaded", function() {
// JavaScript form validation
var checkPassword = function(str)
{
var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}$/;
return re.test(str);
};
var checkForm = function(e)
{
if(this.pwd1.value != "" && this.pwd1.value == this.pwd2.value) {
if(!checkPassword(this.pwd1.value)) {
alert("The password you have entered is not valid!");
this.pwd1.focus();
e.preventDefault();
return;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
this.pwd1.focus();
e.preventDefault();
return;
}
};
var add_employee_form = document.getElementById("add_employee_form");
add_employee_form.addEventListener("submit", checkForm, true);
// HTML5 form validation
var supports_input_validity = function()
{
var i = document.createElement("input");
return "setCustomValidity" in i;
}
if(supports_input_validity()) {
var pwd1Input = document.getElementById("field_pwd1");
var pwd1Rule = "Password must contain at least 6 characters, including UPPER/lowercase and numbers.";
pwd1Input.setCustomValidity(pwd1Rule);
var pwd2Input = document.getElementById("field_pwd2");
var pwd2Rule = "Please enter the same Password as above.";
// input onchange event handlers
pwd1Input.addEventListener("change", function() {
this.setCustomValidity(this.validity.patternMismatch ? pwd1Rule : "");
if(this.checkValidity()) {
pwd2Input.pattern = this.value;
pwd2Input.setCustomValidity(pwd2Rule);
} else {
pwd2Input.pattern = this.pattern;
pwd2Input.setCustomValidity("");
}
}, false);
pwd2Input.addEventListener("change", function() {
this.setCustomValidity(this.validity.patternMismatch ? pwd2Rule : "");
}, false);
}
}, false);
</script>
Change your function to have this at the top:
if(!this.pwd1.value) return;
javascript will return false for values of null or blank so this says return if false.
Full function:
var checkForm = function(e)
{
if(!this.pwd1.value) return;
if(this.pwd1.value != "" && this.pwd1.value == this.pwd2.value) {
if(!checkPassword(this.pwd1.value)) {
alert("The password you have entered is not valid!");
this.pwd1.focus();
e.preventDefault();
return;
}
} else {
alert("Error: Please check that you've entered and confirmed your password!");
this.pwd1.focus();
e.preventDefault();
return;
}
};

Why my below javascript code in asp.net not working?

<script language="javascript" type="text/javascript">
function validate() {
summary += isvalidFirstName();
summary += isvalidMobile();
summary += checkPassword();
summary += checkEmail();
if (summary != "") {
alert(summary);
return false;
} else
return true;
}
function isvalidFirstName() {
var uid;
var temp = document.getElementById("<%=txtFirstName.ClientID %>");
uid = temp.value;
if (uid == "") {
return ("Please enter firstname" + "\n");
} else
return "";
}
function isvalidMobile() {
var mob = /^[1-9]{1}[0-9]{9}$/;
var txtMob = document.getElementById(txtMobile);
if (mob.test(txtMob.value) == false) {
alert("Please enter valid mobile number");
txtMob.focus();
return false;
} else
return true;
}
function checkPassword(inputtxt) {
var pass = /^[A-Za-z]\w{7,14}$/;
if (inputtxt.value.match(pass)) {
alert("Password is correct");
return true;
} else {
alert("Wrong...!");
return false;
}
}
function checkEmail(inputtxt) {
var mail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (inputtxt.value.match(mail)) {
return true;
} else {
alert("Please enetr a valid email id");
return false;
}
}
</script>
I have added the above javascript code inside an .ASPX page and called the function validate on button click but it is not working. Can anyone help me?

retain form values onclick after javascript validation fails

This is part of an assignment. Everything that's supposed to work, already works, but there's something that bothers me. The only purpose of the code so far is to test our ability to validate from data. Anyway, right now the validate() function is attached to a submit button:
<input type="submit" value="Find Love" onclick="validate()">
When any validation fails, all the text boxes, drop downs, etc. are cleared, but I want them to retain their values and just focus on the first incorrect value (retaining their values is more important to me at this point). The actual Does that require some modification of the onclick function or a different function all together? Please help. If you need to see the javascript I can post that as well.
function validate()
{
var blnValid = true;
if(isBlank("txtFName"))
{
blnValid = false;
alert("First name cannot be blank!")
document.getElementById("txtFName").focus();
}
if(blnValid)
{
if(isBlank("txtLName"))
{
blnValid = false;
alert("Last name cannot be blank!")
document.getElementById("txtLName").focus();
}
}
if(blnValid)
{
if(isBlank("txtAge"))
{
blnValid = false;
alert("Age cannot be blank!")
document.getElementById("txtAge").focus();
}
}
if(blnValid)
{
var strInput = document.getElementById("txtAge").value;
if(!isInt(strInput))
{
blnValid = false;
alert("You must enter a valid number in the age field.")
document.getElementById("txtAge").select();
}
}
if(blnValid)
{
if(document.getElementById("selUserGender").selectedIndex <= 0)
{
alert("Please select your gender");
blnValid = false;
}
}
if(blnValid)
{
if(document.getElementById("selFindGender").selectedIndex <= 0)
{
alert("Please select your gender");
blnValid = false;
}
}
if(blnValid)
{
blnChecked = false;
arRadio = document.forms[0].rdbAgeRange;
for (var i = 0; i < arRadio.length; i++)
{
if(arRadio[i].checked)
{
blnChecked = true;
break;
}
}
if (!blnChecked)
{
alert("You must select an age group.");
blnValid = false;
}
}
if(blnValid)
{
if(!document.getElementById("chkSkeeball").checked
&& !document.getElementById("chkAir").checked
&& !document.getElementById("chkCliff").checked
&& !document.getElementById("chkHamster").checked)
{
blnValid = false;
alert("You must select a hobby.")
}
}
return blnValid;
}
function isInt(strValue)
{
var validNums = "0123456789";
var blnIsNumber = true;
var tempChar;
for (var i = 0; i < validNums.length; i++)
{
tempChar = strValue.substr(i, 1);
if (validNums.indexOf(tempChar) == -1)
{
return false;
}
}
return true;
}
function isBlank(elementID)
{
if(document.getElementById(elementID).value.length == 0)
{
return true;
}
return false;
}
Your problem is actually your HTML. Nothing in your Javascript is going to clear the elements but because you're using onClick the form is actually submitting anyway. I assume that it probably just submits back to the page and clears everything. Instead of onClick use onSubmit in the form element:
<form method="post" action="url_of_action" onSubmit="return validate()">
If it's not valid it will prevent the form from submitting.
Missing semi-colons:
if(isBlank("txtFName"))
{
blnValid = false;
alert("First name cannot be blank!") //here
document.getElementById("txtFName").focus();
}
if(blnValid)
{
if(isBlank("txtLName"))
{
blnValid = false;
alert("Last name cannot be blank!") //and here
document.getElementById("txtLName").focus();
}
}
if(blnValid)
{
if(isBlank("txtAge"))
{
blnValid = false;
alert("Age cannot be blank!") //and here
document.getElementById("txtAge").focus();
}
}

Categories

Resources