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;
}
}
Related
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);
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'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;
}
}
I take full advantage of GMail's wildcard feature (username+wildcard#gmail.com). Unfortunately it seems that most developers don't understand that + is valid in an email address. This makes trying to unsubscribe a real chore sometimes.
Take TicketMaster for example... immediately you notice that they didn't even bother escaping the email address, so the text field defaults to "user wilcard#gmail.com". Not a problem, we can just add the + manually. Once Submit is clicked, you'll notice the validation stops you right in your tracks. What now?
Most users would have to further contact TicketMaster and attempt to explain the situation. I opened up FireBug to investigate. That's when I noticed this whopping 74 line email validation function with so much redundancy it's ridiculous. My favorite check is on line 20, informing the user that his/her email cannot have more than one #. Unreal. My second favorite part is the TWO regular expressions used!
Imagine... someone was paid money for this... and by the looks of it, they were paid by the line count.
//Validates the email
function validateOptoutEmail(object) {
var emailStr = object.value;
if(emailStr == '' || emailStr == null) {
alert('Email can not be empty. Please provide email');
object.value = '';
object.focus();
return false;
} else if(Trim(emailStr).length == 0) {
alert('Email can not be empty. Please provide email');
object.value = '';
object.focus();
return false;
} else {
var atcount=0;
for(var i=0;i<emailStr.length;i++) {
if(emailStr.charAt(i)=='#') atcount++;
}
if(atcount>1) {
alert('Invalid email. Email cannot have more than one #');
object.value = '';
object.focus();
return false;
}
if(emailStr.indexOf('.') == -1) {
alert('Invalid email. Email must have one dot');
object.value = '';
object.focus();
return false;
}
if(emailStr.indexOf('..')!= -1) {
alert('Invalid email. Email cannot have consecutive dots');
object.value = '';
object.focus();
return false;
}
var dotpos=0;
for(var i=dotpos;i< emailStr.length;i++) {
var ichar=emailStr.charAt(i);
if(ichar=='.') dotpos=i;
}
for(var i=dotpos+1;i< emailStr.length;i++) {
var ichar=emailStr.charAt(i);
if((!isNaN(ichar)) || (ichar == '_')) {
alert('Invalid email. Email cannot have numbers or _ after dot');
object.value = '';
object.focus();
return false;
}
}
var pattern2=/^([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
var pattern1=/^[0-9a-zA-Z\-\_.]+#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (pattern1.test(emailStr)) {
if(pattern2.test(emailStr)) {
return true;
} else {
alert('Invalid email');
object.value = '';
object.focus();
}
return true;
} else {
alert('Invalid email');
object.value = '';
object.focus();
return false;
}
alert('Invalid email');
object.value = '';
object.focus();
return false;
}
}
I eventually just put a break point in FireBug and changed the value of the email address passed into the validation function. From there everything worked fine...
All that said, how can we get the word out there that + is valid in an email address? Too often, I'm unable to use the email address that I want to use for certain web sites because developers simply aren't aware of what constitutes a valid email address.
Point them at the rfc:
https://www.rfc-editor.org/rfc/rfc5322#page-10
3.2.3 states "+" is a valid atom