I've got a classic input validation for an email and a password, but for some reason my logic doesn't work and I can't figure out the part where it fails. This is code I've refactored from some one else and it bugging me quite a lot now
function Validation() {
this.regex = {
email: new RegExp(/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9]+\.[a-zA-Z0-9-]+/),
password: new RegExp(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{6,13}/),
},
this.email = function () {
let valElement = document.getElementById("mail");
console.log(valElement);
let valueR = valElement.value.toString();
console.log(valueR);
let erorrEl = document.getElementById("error");
let validate_mail = valueR.length == 0 && this.regex.email.test(valueR);
console.log(validate_mail);
console.log(this.regex.email);
if(!validate_mail){
valElement.className = "invalid";
erorrEl.innerHTML = "Please enter a correct email";
erorrEl.className = "error active"
console.log("not validated email");
event.preventDefault();
}else{
valElement.className = "valid";
erorrEl.innerHTML = "";
erorrEl.className = "error"
console.log("validated email");
}
}
this.password = function () {
let valElement = document.getElementById("pass");
let valueR = valElement.value;
let erorrEl = document.getElementById("error2");
let validate_pass = valueR.length == 0 && this.regex.password.test(valueR);
if(!validate_pass){
valElement.className = "invalid";
erorrEl.innerHTML = "Please enter a correct password";
erorrEl.className = "error active"
console.log("not validated password");
event.preventDefault();
}else{
valElement.className = "valid";
erorrEl.innerHTML = "";
erorrEl.className = "error"
console.log("validated password");
}
}
this.form = function(){
if(this.password && this.email){
}else{
}
}
}
var Valdator = new Validation();
Valdator.email();
Valdator.password();
Usually I'm calling these Valdator email and password functions in another file where it's a request from an API, but the idea is the same here, I don't think that woould make a difference
Your RegEx is never being executed because valueR.length == 0 will evaluate to false, which short-circuits your && before it can execute the second part. Remember that if you are AND-ing two statements and the first statements evaluates to false, there is no need to evaluate the second statement because both false && true and false && false evaluate to false.
That being said, it makes no sense to check for valueR.length == 0 as a pre-condition for evaluating a RegEx on valueR - why would we run an RegEx on a 0-length string? You should flip this logic to !==.
And please always use === or !== in the future, as == gets messy with type conversion.
let validate_pass = valueR.length !== 0 && this.regex.password.test(valueR);
Related
I want to check the input if there is a validate emailadress. This is the function I use
function validateEmailAddress(input) {
var regex = /[^\s#]+#[^\s#]+\.[^\s#]+/;
if (regex.test(input)) {
return 1;
} else if (regex.test(input) == null || regex.test(input) == ("")) {
return 0;
} else {
return -1;
}
}
This function is used there
savePerson: function () {
$('#accountid').prop('disabled', false);
let email = $('#emailaddresses').val();
if (validateEmailAddress(email) == -1) {
alert("This email isn't validate");
return;
}
So I have to check if the input field is empty. If this is happening, the data should be validate. If the inputfield isn't an emailaddress like "dasfasf232" it has to show an alert. Only if the email is valid (like it includes an # and a dot). At the moment I get an alert when the emailfield is empty. But that should not happen.
I solved my Problem. The line I had the Problem was
not necessary. So I deleted the "else if" statement. Now it looks like this
function validateEmailAddress(input) {
var regex = /[^\s#]+#[^\s#]+\.[^\s#]+/;
if (regex.test(input)) {
return 1;
} else {
return -1;
}
}
Now in the other part I check if the email, which was typed in isn't empty and (&&) if the email is -1 (the value when the email is invalid). If one of these is true the if-statement shows an alert.
savePerson: function () {
$('#accountid').prop('disabled', false);
let email = $('#emailaddresses').val();
if (email !== "" && validateEmailAddress(email) === -1) {
alert("Use a valid emailaddress");
return;
}
Now I can save my Data in Database even though the email-inputfield is empty.
// Try this function
function ValidateEmail(inputText)
{
var mailformat = /^w+([.-]?w+)*#w+([.-]?w+)*(.w{2,3})+$/;
if(inputText.value.match(mailformat))
{
alert("You have entered a valid email address!"); //The pop up alert for a valid email address
document.form1.text1.focus();
return true;
}
else
{
alert("You have entered an invalid email address!"); //The pop up alert for an invalid email address
document.form1.text1.focus();
return false;
}
}
I'm getting an array of Strings, and if the array has items I want to do one thing and if not I want to do the other. I'm not sure how to check if the array is empty of not. Also when stepping through my code in chrome debugger even if the array has items in it the length is still 0 so I can't use formErrors.length > 0.
Here's my code for getting the errors. This works fine and returns an array of error strings or an empty array:
var formErrors = validateFormData(formData);
function validateFormData(data) {
var errors = [];
if (data["title"].length == 0) {
errors["title"] = "Project title required";
}
if (data["client"].length == 0) {
errors["client"] = "Client name required";
}
if (data["date"].length == 0) {
errors["date"] = "Date required";
} else if (!isValidDateFormat(data["date"])) {
errors["date"] = "Date format invalid - Format: dd/mm/yyyy";
}
if (data["status"] == "") {
errors["status"] = "Please select current status for this project";
}
if (data["type"] == "") {
errors["type"] = "Please select a project type";
}
if (data["extras"].length == 0) {
errors["extras"] = "You must select at least one extra for this project";
}
return errors;
}
Then I want to do one thing if there's no errors and another if there is. But this is the bit that won't work for me.
if (formErrors !== {}) {
displayFormErrors(formErrors);
event.preventDefault();
}
else {
clearForm();
}
I've tried multiple ways and nothing has worked so far. Any help is appreciated, thank you!
EDIT
I can't use the .length on the array cause the length is 0 even when it has data.
Screenshot of chrome debugger
I'm slightly confused about what people are asking sorry, i'm not an expert here is my full code to get a better understanding of what i'm trying to do.
$(document).ready(function () {
$('#submit').on("click", onSubmitForm);
function onSubmitForm(event) {
clearErrorMessages();
var formData = getFormData();
var formErrors = validateFormData(formData);
if (formErrors) {
displayFormErrors(formErrors);
event.preventDefault();
}
else {
clearForm();
// Do other stuff
}
}
function clearForm() {
$('#title').val("");
$('#client').val("");
$('#date').val("");
$('#status').val("planning");
$('#description').val("");
$('.type').prop('checked', false);
$('.extra').prop('checked', false);
$('#title').focus();
}
function clearErrorMessages() {
$(".uk-text-danger").html("");
}
function getFormData () {
var data = [];
data["title"] = $('#title').val();
data["client"] = $('#client').val();
data["date"] = $('#date').val();
data["status"] = $('select#status option:selected').val();
data["description"] = $('#description').val();
if ($("input[name='type']:checked").length > 0) {
data["type"] = $("input[name='type']:checked").val();
}
else {
data["type"] = "";
}
data["extras"] = [];
$.each($("input[name='extras[]']:checked"), function(index, radio) {
data["extras"].push(radio.value);
});
return data;
}
function validateFormData(data) {
var errors = [];
if (data["title"].length == 0) {
errors["title"] = "Project title required";
}
if (data["client"].length == 0) {
errors["client"] = "Client name required";
}
if (data["date"].length == 0) {
errors["date"] = "Date required";
} else if (!isValidDateFormat(data["date"])) {
errors["date"] = "Date format invalid - Format: dd/mm/yyyy";
}
if (data["status"] == "") {
errors["status"] = "Please select current status for this project";
}
if (data["type"] == "") {
errors["type"] = "Please select a project type";
}
if (data["extras"].length == 0) {
errors["extras"] = "You must select at least one extra for this project";
}
return errors;
}
function displayFormErrors(errors) {
for (var field in errors) {
var errorElementId = field + "Error";
$('#' + errorElementId).html(errors[field]);
}
} });
Sorry if this is too much i'm not sure what else to do.
An empty array, string or object is "falsy" in JavaScript.
That is, you can pass the array, string or object directly into the if conditional and it will run depending on if something is in there or not.
if ([]) {
// this will never run
}
if ('') {
// this won't run either
}
if ({}) {
// nor will this
}
var errors = {}; inside the validateFormData function.
And then compare the the object like this.
if (JSON.stringify( formErrors ) !== '{}') { //do something}else { //do something}
Where are you verifying if the formErrors is empty? This verification (the if-else) should be inside the function which submits the form.
Also try using:
if (formErrors.length > 0)
instead of:
if (formErrors !== {})
I have a log in form and am trying to display an error message if the log is incorrect.
For example;
If (email and password match) then set validUser to true.
If validUser equals true then redirect to home page
Else redirect them back to log in and display one of 3 messages...
Messages are:
'Log in unsuccessful' if both email and password are incorrect
'Password incorrect' if just the password is wrong
'Email incorrect' if just the email is wrong
Is it possible to have a loop to do all this? I can't figure it out....
Trying something like this too:
if (validUser==false)
{
$("message").show();
}
else if ( ..........)
{
$("passwordmessage").show();
}
I also want to display a message on the page and so far using this:
document.getElementById('message').style.display = ""
Here is my code: http://jsfiddle.net/2pkn1qrv/
So, how could I use if statements to do this and how can I correctly display a html page element using javascript or jquery?
Please ask if you need any more code or require clarification.
P.s. these are my users details
var USERS = {
users: []
};
function User(type, email, password) {
this.type = type;
this.email = email;
this.password = password;
}
var A = new User("rep", "a#a.com", "a");
USERS.users.push(A);
var B = new User("rep", "b#b.com", "b");
USERS.users.push(B);
var C = new User("customer", "c#c.com", "c");
USERS.users.push(C);
var D = new User("grower", "d#d.com", "d");
USERS.users.push(D);
module.exports = USERS;
You wont be having 3 conditions in that case. you will check email availability and password match. If anyone fails, you can display the message. I couldnt test your code but this will be the logic and i assume Users.user[x].email is the list of emails from your database. If yes, sorry to say that its a bad practise.
validUser = false;
emailAvailable = false;
passwordIncorrect = false;
for (var x in USERS.users) {
if(!emailAvailable && emailLog === USERS.users[x].email){
emailAvailable = true;
} //Checks whether email is available.
if(emailAvailable && passwordLog === USERS.users[x].password){
passwordIncorrect = true;
break;
} //Checks whether the password is correct for that email.
} // end of for
if(!emailAvailable){
console.log("Email is incorrect");
}
else if(emailAvailable && !passwordIncorrect){
console.log("Password is incorrect");}
else{
validUser = true;
console.log("Valid User");
}
if(validUser){
//redirect
}
I think my way is it worth to give a try:
First: create a Javascriptobject:
function ruleToCheck(errorRule, errorMsgContainer)
{
this.errorCondition = errorRule;
this.errorMessage = errorMsgContainer;
}
after that create an array and fill it with your rules:
var rulesList = new Array();
rulesList.push(new ruleToCheck("validUser === true", "message"));
...
Then loop through the array:
var rulesListLength = rulesList.length;
var index = 0;
while (index < rulesListLength)
{
index++;
...
}
The secret of success is the powerful eval() function within the while() loop:
if (eval(rulesList[index].errorCondition))
{
$("#"+rulesList[index].errorMessage).show();
break;
//If 'break does not work, use 'index = rulesListLength'
}
Hope it was helpful or at least leaded you into the right direction.
By the way, take care of the comments on your question.
I'm quite new to JavaScript and I'm having an issue with a contact form.
I have 2 if statements and I return false at the end of the second one, but when I execute this, with both fields empty, its happy, and my error msgs pop up, and the email doesn't send. but if I only enter information in the second input field, it thinks the form is filled out, even with the first field empty.
How do I stop the email from sending if either one of the if statements is false?
My code
function checkForm(){
if (streetAddress.value == "") {
addressErrorMsg.style.display="block";
}
if (fullname.value == "") {
nameErrorMsg.style.display="block";
return false;
}
else{
return true;
}
}
Keep track of the state and have one return statement at the end.
function checkForm(){
var isValid = true;
if (streetAddress.value == "") {
addressErrorMsg.style.display="block";
isValid = false;
}
if (fullname.value == "") {
nameErrorMsg.style.display="block";
isValid = false;
}
return isValid;
}
And looking at your code, I am hoping you have
var addressErrorMsg = document.getElementById("SomeId");
above your code and you are not just using the id to reference the element.
function checkForm(){
var validate = true;
if (streetAddress.value == "") {
addressErrorMsg.style.display="block";
validate = false;
}
if (fullname.value == "") {
nameErrorMsg.style.display="block";
validate = false;
}
return validate;
}
I have JavaScript form validation functions like so:
function validate_name(field)
{
if (field == "") return "Please enter the name.\n";
return "";
}
function validate_specialty(field)
{
if (field == "") return "Please enter the specialty.\n";
return "";
}
function validate_location(field)
{
if (field == "") return "Don't forget the location.\n";
return "";
}
where the function that is called from the form's onSubmit is:
function validate_fields(form)
{
fail = validate_name(form.name.value);
fail += validate_specialty(form.specialty.value);
fail += validate_location(form.location.value);
if (fail == "")
return true;
else
{
alert(fail);
return false;
}
}
This works fine but I have decided that I don't want all three to necessarily be required. It would be great if I could make these three optional, such that if any one of these fields is filled in, it would validate true, but if all three fields are empty, I could throw an alert and validate false.
Any help is much appreciated.
You can do that by capturing the results separately, and testing with an OR grouping.
function validate_fields(form)
{
fail1 = validate_name(form.name.value);
fail2 = validate_specialty(form.specialty.value);
fail3 = validate_location(form.location.value);
if (fail1 == "" || fail2 == "" || fail3 == "")
return true;
else
{
alert(fail1 + fail2 + fail3);
return false;
}
}