How to set the focus to first invalid form field?


#1

I’m trying to use the onFormSubmit attribute to set the focus on the first invalid form field instead of remaining on the Submit button. Whatever I try seems to have no effect. Has anyone else been successful in doing something similar?


#2

As an example of what I’m trying to accomplish, take a look at this code:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Simple Form Validation Using Only WAI-ARIA aria-describedby &amp; jQuery .focus()</title>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(document).ready(function(e) {
	$('#signup').submit(function() {
		$('#first-error, #last-error, #password-error, #email-error').remove();
		$('#first, #last, #password, #email').removeAttr('aria-invalid');
		if ($('#first').val() === '') {
			$('#first').after('<span id="first-error">Please enter your first name.</span>').attr({"aria-describedby": "first-error", "aria-invalid": "true"});
		}
		if ($('#last').val() === '') {
			$('#last').after('<span id="last-error">Please enter your last name.</span>').attr({"aria-describedby": "last-error", "aria-invalid": "true"});
		} 
		if ($('#password').val() === '') {
			$('#password').after('<span id="password-error">Please enter your password in the required format.</span>').attr({"aria-describedby": "password-error password-format", "aria-invalid": "true"});
		} 
		if ($('#email').val() === '') {
			$('#email').after('<span id="email-error">Please enter your email in the format name@domain.com.</span>').attr({"aria-describedby": "email-error", "aria-invalid": "true"});
		} 
		if ($('#first').val() === '') {
			$('#first').focus();
		} else if ($('#last').val() === '') {
			$('#last').focus();
		} else if ($('#password').val() === '') {
			$('#password').focus();
		} else if ($('#email').val() === '') {
			$('#email').focus();
		}
		return false;
	});
});
</script>
</head>

<body>
<h1>Simple Form Validation Using  WAI-ARIA aria-describedby, aria-required, aria-invalid, &amp; <a href="http://api.jquery.com/focus/">jQuery .focus()</a></h1>
<form name="signup" id="signup" method="post" action="">
  <p>
    <label for="first">First Name *</label><br>
    <input type="text" name="first" id="first" aria-required="true">
  </p>
  <p>
    <label for="last">Last Name *</label><br>
    <input type="text" name="last" id="last" aria-required="true">
  </p>
  <p>
    <label for="password">Password *</label><br>
    <input type="text" name="password" id="password" aria-describedby="password-format password-error" aria-required="true">
    <span id="password-format">8 digits, 1 upper case, 1 number, 1 special character </span>
  </p>
  <p>
    <label for="email">Email *</label><br>
    <input type="text" name="email" id="email" aria-required="true">
  </p>
  <p>
    <input type="submit" name="button" id="button" value="Submit">
  </p>
</form>
</body>
</html>

#3

@karl.kasischke Here is an example I found on stack overflow.

up vote
29
down vote
accepted
First of all you need to save your validator to a variable so you can use it in the click handler:

var validator = $("#test-form").validate({ /* settings */ });
Then in the validate handler, you can manually call the focusInvalid function from the validator variable:

  $("#validate").click(function() {
        if ($("#test-form").valid()) 
              alert("Valid!");
        else
              validator.focusInvalid();

        return false;
  });

#4

Does this mean that HubSpot forms are using the jQuery Validate plugin? That would make things simpler. I guess I assumed HubSpot forms were using their own proprietary validation functions.


#5

@karl.kasischke I’m actually not a 100% sure on what the engineering team uses for validation. I was referring to you using your own validation on top of it.


#6

@karl.kasischke We were successfully able to prevent form and run custom form validation on and overcome the hubspot validation. It was challenging as none of the jquery functions were able to prevent form submit. if you require any help in this concern let us know we will provide a demo for you. We love to help to over come this constraint, motive is simple to help you with your challenges so you keep enjoying and working on hubspot COS platform.

Thanks


#7

@dan_hmonks I really appreciate the offer! I will keep it in mind.


#8

@pmanca, Hey, we will be publishing blog on form too, were we focus on interactivity and customisation of hubspot forms, I guess next week it will go live, with motive to let all hubspot community is benefited, HubSpotters explore more, do more innovation using their skill set. they love and enjoy working on this platform.

Will share link : hope you like it.

Thanks :slight_smile:


#9

@dan_hmonks That sounds great please share the link when it goes live.


#10

What I’ve done for now, until I can find a better solution:

<script>
  hbspt.forms.create({ 
    portalId: '[INSERT HUBSPOT PORTAL ID HERE]',
    formId: '[INSERT HUBSPOT FORM ID HERE]',
    onFormReady: function($form, ctx) {
      console.log('onFormReady function triggered.');
      jQuery('.hs-submit .hs-button').click( function() {
        console.log('jQuery onclick function triggered.');
      });
      jQuery('#hsForm_[INSERT HUBSPOT FORM ID HERE]').validate({
        errorPlacement: function(error, element) {
          error.appendTo("label[for="+jQuery(element).attr('id')+"]");
        },
	errorElement: "em"
      });
      jQuery('form').removeAttr('novalidate');
    },
    onFormSubmit: function($form) {
      console.log('onFormSubmit function triggered.');
    } 
  });
</script>

I would have preferred to use the onFormSubmit function, but if you watch the console, it does not seem to fire.


#11

@pmanca @karl.kasischke
We got on hubspot forms with custom validation too, I hope this might also be intresting for you :slight_smile:

Hubspot COS, forms with custom validation


#12

@karl.kasischke @pmanca,

Now you can uses any js library to validate forms on hubspot, performs what ever you want to,
customise manipulation and other stuff and submitting with ease.
Thanks :slight_smile:


#13

@dan_hmonks Great! thanks for the post and link


#14

@pmanca we have published blog here is article that speaks about customization on forms :slight_smile:
blog on custom forms interactivity

Soon we planning to show forms : with google materials, animate.css and forms evolving steps


#15

Hello!

I've created an Angular directive to solve this problem. You can check it here ngx-scroll-to-first-invalid.

Steps:

1.Install the module:

`npm i @ismaestro/ngx-scroll-to-first-invalid --save`

2.Import the NgxScrollToFirstInvalidModule:

    import {BrowserModule} from '@angular/platform-browser';
    import {NgModule} from '@angular/core';
    import {NgxScrollToFirstInvalidModule} from '@ismaestro/ngx-scroll-to-first-invalid';

    @NgModule({
        imports: [
            BrowserModule,
            NgxScrollToFirstInvalidModule
        ],
        bootstrap: [AppComponent]
    })
    export class AppModule { }

3.Use the directive inside a form:

<form [formGroup]="testForm" ngxScrollToFirstInvalid>
  <input id="test-input1" type="text" formControlName="someText1">
  <button (click)="saveForm()"></button>
</form>

Hope it helps!
:slight_smile: