Skip to main content

How to use form validations(Jquery validations) in step form?

<!DOCTYPE html>
<html>
<head>
<title>Multi-file Upload</title>
<style>
fieldset {
  display: none;
}

fieldset:first-child {
  display: block;
}

button {
  margin-top: 10px;
}

.prev {
  margin-right: 10px;
}
.drop-zone {
  border: 2px dashed #ccc;
  width: 300px;
  height: 200px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
}
.file-preview {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
}
.file-item {
  display: flex;
  align-items: center;
  margin-right: 10px;
  margin-bottom: 10px;
}
.file-item img {
  width: 50px;
  height: 50px;
  margin-right: 5px;
}
.remove-btn {
  cursor: pointer;
  color: red;
  font-weight: bold;
}
.file_preview_error{
  color:red;
}
.error{
  color:red;
  display:block;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script>
$(document).ready(function() {
  // Initialize validation for the form
  $('#stepForm').validate({
    rules: {
      name: 'required',
      email: {
        required: true,
        email: true
      },
      password: {
        required: true,
        minlength: 6
      },
      confirmPassword: {
        required: true,
        equalTo: '#password'
      },
      username: 'required',
      address: 'required',
      city: 'required'
    },
    messages: {
      // Customize error messages for each field if needed
    },
    errorPlacement: function(error, element) {
      // Customize error placement if needed
      error.insertAfter(element);
    }
  });
  function thirdStepJqueryValidations(){
    $("#stepForm").validate({
      rules: {
        username: "required",
        },
      // In 'messages' user have to specify message as per rules
      messages: {
        username: "Username is required."
      }
    });
    return $("#stepForm").valid();
  }
  // Step navigation
  var currentStep = 0;
  var fieldsets = $('#stepForm fieldset');
  var stepsCount = fieldsets.length;

  function navigateTo(step) {
    // Hide all fieldsets
    fieldsets.hide();
    // Show the selected step
    $(fieldsets[step]).fadeIn('slow');
    // Disable previous button if on the first step
    $('.prev').prop('disabled', step === 0);
    // Change the text of the next button on the last step
    if (step === stepsCount - 1) {
      $('.next').text('Submit');
    } else {
      $('.next').text('Next');
    }
  }
  function dropFileValidation(){
    var dropZone = $('#file_preview');
    $(".file_preview_error").text("");
    if (dropZone.is(':empty')) {
        // The drop zone is empty
        // Perform your validation logic here or take appropriate actions
  /*       console.log("The drop zone is empty."); */
        $(".file_preview_error").text("This field is required.");
        return false;
      }
    return true;
  }
  $('.next').click(function() {
      console.log(currentStep);
      if(currentStep == 2){
        if(!thirdStepJqueryValidations() || !dropFileValidation()) {
          dropFileValidation();
          return false;
        }
      }
    if ($('#stepForm').valid()) {
        currentStep++;
        navigateTo(currentStep);
    }
  });
  $('.prev').click(function() {
    currentStep--;
    navigateTo(currentStep);
  });
});

window.addEventListener("DOMContentLoaded", () => {
  const dropZone = document.getElementById("dropzone");
  const filePreview = document.getElementById("file_preview");
  // Handle file drop
  dropZone.addEventListener("drop", (e) => {
    e.preventDefault();
    const files = e.dataTransfer.files;
    handleFiles(files);
  });
  // Handle file drag over
  dropZone.addEventListener("dragover", (e) => {
    e.preventDefault();
  });
  // Handle file input change
  dropZone.addEventListener("click", () => {
    const fileInput = document.createElement("input");
    fileInput.type = "file";
    fileInput.multiple = true;
    fileInput.accept = "image/*";
    fileInput.addEventListener("change", (e) => {
      $(".file_preview_error").text("");
      const files = e.target.files;
      handleFiles(files);
    });
    fileInput.click();
  });
  // Handle file removal
  filePreview.addEventListener("click", (e) => {
    if (e.target.classList.contains("remove-btn")) {
      const fileItem = e.target.parentElement;
      const fileName = fileItem.getAttribute("data-file-name");
      fileItem.remove();
    }
  });
  function handleFiles(files) {
    for (const file of files) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const fileContent = e.target.result;
        displayFile(file, fileContent);
      };
      reader.readAsDataURL(file);
    }
  }
  function displayFile(file, fileContent) {
    const fileItem = document.createElement("div");
    fileItem.classList.add("file-item");
    fileItem.setAttribute("data-file-name", file.name);
    const image = document.createElement("img");
    image.src = fileContent;
    // Create the input element
    const inputElement = document.createElement("input");
    // Set the input type and value attributes
    inputElement.setAttribute("type", "hidden");
    inputElement.setAttribute("name", "files[]");
    inputElement.setAttribute("value", fileContent + "?filename=" + file.name);
    const fileName = document.createElement("span");
    fileName.innerText = file.name;
    const removeBtn = document.createElement("span");
    removeBtn.classList.add("remove-btn");
    removeBtn.innerText = "Remove";
    fileItem.appendChild(image);
    fileItem.appendChild(inputElement);
    fileItem.appendChild(fileName);
    fileItem.appendChild(removeBtn);
    filePreview.appendChild(fileItem);
  }
});
</script>
</head>
<body>
<form id="stepForm" method="post">
  <fieldset>
    <h2>Step 1</h2>
    <input type="text" name="name" id="name" placeholder="Name">
    <input type="email" name="email" id="email" placeholder="Email">
    <button type="button" class="next">Next</button>
  </fieldset>
  <fieldset>
    <h2>Step 2</h2>
    <input type="password" name="password" id="password" placeholder="Password">
    <input type="password" name="confirmPassword" id="confirmPassword" placeholder="Confirm Password">
    <button type="button" class="prev">Previous</button>
    <button type="button" class="next">Next</button>
  </fieldset>
  <fieldset>
    <h2>Uploader</h2>
    <input type="text" name="username" >
    <div class="drop-zone" id="dropzone">
    <span>Drag and drop files here</span>
  </div>
  <div class="file-preview" id="file_preview"></div>
  <div class="file_preview_error"></div>

    <button type="button" class="prev">Previous</button>
    <button type="button" class="next">Next</button>
  </fieldset>
  <fieldset>
    <h2>Step 3</h2>
    <input type="text" name="address" id="address" placeholder="Address">
    <input type="text" name="city" id="city" placeholder="City">
    <button type="button" class="prev">Previous</button>
    <button type="submit">Submit</button>
  </fieldset>
</form>
</body>
</html>

 

Comments

Popular posts from this blog

How to use inner html value or data in php from javascript(innerHTML)?

 use inner html value or data in php from javascript(innerHTML)? <html> <body> <p id="demo">use inner html value in php(innerhtml)</p> <script>   var jassi = document.getElementById("demo").innerHTML;   //document.write(jassi); </script> <?php $jassi = '<script>document.write(jassi);</script>'; echo $jassi; ?> </body> </html>

How to get store data from WCFM(Best Multi Vendor Marketplace) Plugin?

 Get store data from WCFM(Best Multi Vendor Marketplace) Plugin. global $WCFM, $WCFMmp, $wp, $WCFM_Query, $post; $store_id = ''; if ( isset( $attr['id'] ) && !empty( $attr['id'] ) ) { $store_id = absint($attr['id']); } if (  wcfm_is_store_page() ) { $wcfm_store_url = get_option( 'wcfm_store_url', 'store' ); $store_name = apply_filters( 'wcfmmp_store_query_var', get_query_var( $wcfm_store_url ) ); $store_id  = 0; if ( !empty( $store_name ) ) { $store_user = get_user_by( 'slug', $store_name ); } $store_id    = $store_user->ID; } $user_id = $store_id;  $vendor_data = get_user_meta( $user_id, 'wcfmmp_profile_settings', true ); $street_1 = $vendor_data['address']['street_1']; $street_2 = $vendor_data['address']['street_2']; $city     = $vendor_data['address']['city']; $zip      = $vendor_data['address']['zip&#

How to create login with phone number in woocommerce wordpress?

Create login with phone number in woocommerce wordpress. function wooc_extra_register_fields() {?>        <p class="form-row form-row-wide">        <label for="reg_billing_phone"><?php _e( 'Phone', 'woocommerce' ); ?><span class="required">*</span></label>        <input type="text" class="input-text" name="billing_phone" id="reg_billing_phone" value="<?php esc_attr_e( $_POST['billing_phone'] ); ?>" />        </p>            <?php  }  add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );  function wooc_validate_extra_register_fields( $username, $email, $validation_errors ) { if ( isset( $_POST['billing_phone'] ) ) {    $hasPhoneNumber= get_users('meta_value='.$_POST['billing_phone']);    if ( !empty($hasPhoneNumber)) {      $validation_er