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)
Related
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 want to repeat the code until the user gets the no. right. How do I do this ?
This is the code:-
function getRandomNumber(min,max){
return Math.floor(Math.random()*(max - min + 1 ))+min;
}
randomNumber=(getRandomNumber(1,10));
input=prompt("Please enter a no. between 1 and 10:","");
if(input==randomNumber){
console.log("Good Work");
}else{
console.log("not matched");
}
You could either use a while loop that calls a "break" statement once the user inputs the correct answer, or you could use a function like this:
function getInput(){
input=prompt("Please enter a no. between 1 and 10:","");
if(input==randomNumber){
console.log("Good Work");
}else{
consol.log("not matched");
getInput(); //Gets the user's input again
}
}
Here you go...
Found needs to be set to false before you start, otherwise the function will only run one. There is little point having the function definition inside the while loop, since it will be created as a global variable.
var found = false;
function getRandomNumber(min,max) { return Math.floor(Math.random()*(max - min + 1 ))+min; }
while ( found != true ) {
var randomNumber = getRandomNumber(1,10);
console.log('Random Number is..',randomNumber);
var input = prompt("Please enter a no. between 1 and 10:","");
if ( input == randomNumber ) {
alert('Well Done')
found = true;
} else {
console.log("not matched");
}
}
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 am trying to validate zip codes using an if function with a regex. Can this be done? I currently just have the if function making sure the zip code is 5 numbers.
below is the regex i want to use
(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)
Can someone show me where and how i would add this to the if function below?
var value = $(this).val();
if( value.length<5 || value==$(this).attr('id') ) {
$(this).addClass('error');
error++;
} else {
$(this).addClass('valid');
}
var ZipCode = "(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)";
if (ZipCode.test(98800)) {
// true
} else {
// false
}
Try this
Try this
var filter = "(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)";
if (!filter.test($(this).attr('id').value)) {
$(this).addClass('error');
error++;
}
else
{
$(this).addClass('valid');
}
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;
}
}