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;
}
}
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'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 am using jQuery Steps plugin (LINK HERE). Problem is in one IF statements that returns wizzard to first step (not on step that is currently indexed). All IF statements are working correctly expect this one. That if statemnt is checking if phone number is in correct format:
Here is code:
onFinishing: function (event, currentIndex) {
var filter = /^(([^<>()[\]\\.,;:\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 (!filter.test($("#email").val())) {
$("#emailError").text("e-mail is wrong");
return false;
}
if (!filter.test($("#email2").val())) {
$("#email2Error").text("e-mail is wrong");
return false;
}
var newnum = parseInt($("#numppl").val());
if(Math.floor(newnum) != newnum && !$.isNumeric(newnum)){
$("#numpplError").text("Number error");
return false;
}
if (!($("#numppl").val() >= 1 && $("#numppl").val()<=10)){
$("#numpplError").text("Number error");
return false;
}
if ($("#email").val()!=($("#email2").val())){
$("#email2Error").text("address don't match");
return false;
}
/*IF Statment bellow is bugged */
if ($("#phone").length) {
if(!$("#phone").match(/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/)){
$("#phoneError").text("Wrong format");
return false;
}
}
return true;
},
Make correction in IF Statement in which you commented as bug :
pval = $("#phone").val(); //Store the value of "Phone"
if (pval.length) { //Check for non empty
if(!pval.match(/^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]*([\d]{3})[\.\-\s]?([\d]{4})$/)) { // Check format.
$("#phoneError").text("Wrong format");
return false;
}
}
$("#phone").length isn't same as the length of phone number
inspite of $("#phone").length use ($("#phone").val()).length
similarly inspite of $("#phone").match(regular Expression) use
($("#phone").val()).match(regular Expression)
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;
}