React-stripe-elements: "Required" attribute and basic validaiton

Created on 31 Dec 2017  路  3Comments  路  Source: stripe/react-stripe-elements

I can't find a way to pass required attribute to prevent users from submitting an empty form. If it's not supported what is the best way to perform a basic validation (check if an input is empty and display a validation message)?

Most helpful comment

I believe the best option you'll have is further documented on this page:
https://stripe.com/docs/stripe-js/reference#element-on

You could pass an onChange function to the Element and listen for the complete boolean. It has some rough edges, but just might be what you need to make sure the input is actually filled.

All 3 comments

I believe the best option you'll have is further documented on this page:
https://stripe.com/docs/stripe-js/reference#element-on

You could pass an onChange function to the Element and listen for the complete boolean. It has some rough edges, but just might be what you need to make sure the input is actually filled.

Thanks, @lindleywhite. Here is my approach

stripeElementChange = (element, name) => {
    if (!element.empty && element.complete) {
      this.setState({ [name]: true });
    }
    this.checkEmptyStripeElements();
  }
<CardNumberElement 
   placeholder="Enter your credit card number"
   options={{creditCard: true}}
   name="card_number"
   onChange={(element) => this.stripeElementChange(element, 'card_number')}
/>

With Javascript, you can check if the element is complete by using the payload from the 'change' event.

From the documentation:
https://stripe.com/docs/stripe-js/reference#element-on
change Triggered when any of the following values changes on the Element. The event payload always contains certain keys, in addition to some Element-specific
complete Boolean true聽if the value is well-formed and potentially complete.

Solution via AngularJS 1.6x controller:

card.addEventListener('change', function(event) {

  var displayError = document.getElementById('card-errors');
  if (event.error) {
    displayError.textContent = event.error.message;
  } else {
    displayError.textContent = '';
    }

    //take the negative of event.complete
    **$scope.cardInvalid = !event.complete;**
});

HTML template:

<button type="submit" class="btn btn-sm btn-primary" name="submit" title="Add Payment Info" ng-disabled="addPaymentForm.$invalid || cardInvalid">Add Payment</button>
Was this page helpful?
0 / 5 - 0 ratings

Related issues

max-favilli picture max-favilli  路  5Comments

sonarforte picture sonarforte  路  4Comments

alenadrex picture alenadrex  路  3Comments

stephenhuh picture stephenhuh  路  4Comments

DennisdeBest picture DennisdeBest  路  4Comments