Form hidden field and required validation use

19,791

Solution 1

You can use this trick:

inside HTML form:

<input type="text" name="username" required="required" class="input-hidden">

CSS class:

.input-hidden{
        height:0;
        width:0;
        visibility: hidden;
        padding:0;
        margin:0;
        float:right;
}

Solution 2

You can add a class name for all the required attributes in the html:

<input type="text" name="first_name" class="card-payment-info" required>
<input type="text" name="last_name" class="card-payment-info" required>

and, from js event like a click, you can enable or disable the required attributes:

// disable require:
$(".card-payment-info").attr('required', false);
// enable require
$(".card-payment-info").attr('required', true);

Solution 3

Add a class .hideable to your hideable required inputs. Then use these functions instead of your show() and hide():

function show1() {
//Your show() code here
$('.hideable').attr('required', 'required');
}
function hide1() {
//Your hide() code here
$('.hideable').removeAttr('required');
}

Solution 4

1 - Change the form to "novalidate"

2 - Catch the submit event

3 - Force the browser to check individually each visible input with input.reportValidity()

$('form')
  .attr('novalidate', true)
  .on('submit', function(){
    var isValid = true;
    $('input:visible,select:visible,textarea:visible', this).each(function() {
      // report validity returns validity of input and display error tooltip if needed
      isValid = isValid && this.reportValidity();
      // break each loop if not valid
      return isValid;
    });
    // do not submit if not valid
    return isValid;
  })

I've made a JQuery tool for this that also uses a mutation observer to automatically apply on dynamically created forms.

https://github.com/severinmoussel/VisibilityFormValidator/blob/master/VisibilityFormValidator.js

Share:
19,791
P. Tzik
Author by

P. Tzik

Updated on June 16, 2022

Comments

  • P. Tzik
    P. Tzik almost 2 years

    I have an HTML5/Bootstrap form with hidden fields: style="display: none"

    which i show/hide via jQuery:

    show() | hide()
    

    For field validation i use the attribute required.

    I want to have all my hidden fields as required but when some of them don't appear then the form can't proceed to submission.

    Any thoughts about how can i have validation enabled only to fields displayed by user selections?