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;
}
};
Related
This is the code i have so far:
i have set up the function to detect the input is a valid email input.
i have set up the code to print an error message when there is no input.
No message is needed if email is correct, only when email is invalid.
"use strict";
function validEmail(email) {
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,}))$/;
return re.test(email);
}
function validate() {
var errorMsg = "";
var emailboxInput = document.getElementById("email");
var emailbox = emailboxInput.value.trim();
emailboxInput.value = emailbox;
if (emailbox === "") {
errormsg += "Email cannot be empty.<br>";
}
if (emailbox === (!validEmail(email))
{
}
else {
errorMessage += "Provide a valid email address<br>";
}
else {
errorMsg += "Provide a valid email address<br>";
}
return errorMsg;
}
// submit button
// msg = html area where error messages are displayed
var sendBtn = document.getElementById("form-send");
sendBtn.onclick = function () {
var msgArea = document.getElementById("msg");
var msg = validate();
if (msg === "") {
return true;
} else {
msgArea.innerHTML = msg;
return false;
}
};
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);
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;
}
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" );
I need to disable the submit button until all fields are filled with the rules any tips?
window.onload = $("input[type=submit]").attr("disabled", "disabled");
$(function(){
$("input[type=submit]").attr("disabled", "disabled");
var total = document.getElementById('valor_total'),
descontado = document.getElementById('valor_descontado'),
valor_final = document.getElementById('valor_final'),
vendedor = document.getElementById('vendedor'),
cliente = document.getElementById('cliente'),
no_contrato = document.getElementById('contrato'),
validation;
var f_total = total.value;
var f_descontado = descontado.value;
var f_final = valor_final.value;
var f_vendedor = vendedor.value;
var f_cliente = cliente.value;
var f_no_contrato = no_contrato.value;
$("#numero_contrato").blur(function() {
if ( f_vendedor == "0" || f_cliente == "0" || f_no_contrato == "" || f_total == "0,00" || f_final == "0,00") {
validation = false;
} else {
validation = true;
}
if (validation = true) {
$("input[type=submit]").removeAttr("disabled");
} else {
$("input[type=submit]").attr("disabled", "disabled");
}
});
});
what i'm doin wrong?
I want that user type in the field with id numero_contrato the function runs and enable or not the submit
For starters, try fixing this conditional:
if (validation === true) {
$('input[type=submit]').removeAttr('disabled');
} else {
$('input[type=submit]').attr('disabled', 'disabled');
}
You had a single equals which is used for assignment. You want double or preferably, triple equals. But you can drop those entirely since you're using a boolean: if (validation) { ... }