Jump to content

Custom Form Validation

Recommended Posts

Hey, I'd like to add custom validation to my forms, currently, the forms check if the fields are valid AFTER the user clicks the submit button, I'd like it to be instantaneous when they change something, and the button to be disabled till all fields are valid, I searched into the situation a bit and I'm still not quite able to do much; I can't get it to work and I don't really understand why, here's the current code:

 

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/jquery.validation/1.19.3/jquery.validate.min.js"></script>
  <script>
    $(document).ready(function() {
      var form = $('#your-form-id');
      var submitButton = form.find('button[type="submit"]');
      
      form.validate({
        rules: {
          'first-name': {
            required: true
          },
          'last-name': {
            required: true
          },
          // Other fields' rules
        },
        messages: {
          'first-name': {
            required: "First name is required."
          },
          'last-name': {
            required: "Last name is required."
          },
          // Other fields' error messages
        }
      });
    
      // Disable the submit button until all fields are valid
      form.on('keyup change', function() {
        if (form.valid()) {
          submitButton.prop('disabled', false);
        } else {
          submitButton.prop('disabled', true);
        }
      });
    });
  </script>

any help would be much appreciated and thanks in advance!

Best Regards,
kaffae 

Link to comment
  • 10 months later...
  • Replies 1
  • Views 1.8k
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Create an account or sign in to comment

You need to be a member in order to leave a comment


×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.