Search code examples
javascriptreactjsvalidation

How to use checkValidity with a link button?


I have a form with a button that is a link (with 'to' attribute) and I'm using checkValidity() to use required attribute, but if I use to={{pathname...}} it changes to the link without make validation

This is my form:

<Form id="form">
   <Input required /* ... */></Input>
   <Button type="submit" onClick={this.send} tag={Link}
       to={{pathname: '/something', 
       param: this.state.param}}> 
   </Button>
</Form>

This is validation code:

send(){
   var $myForm = $('#form');

   if(! $myForm[0].checkValidity()){
       $myForm[0].reportValidity()
   }
}

if I remove " tag={Link}" from button it makes validation, but without changing path

if it has " tag={Link}" it change to the pathname without validation

Someone can help?


Solution

  • Which UI Framework / Kit you are using?

    Is Link imported from react-router? (react-router-dom)

    First of all, using jQuery inside your react component is probably not a good idea.

    You should be able to stop the event if the form is not valid:

    - send() {
    + send(e){
        var $myForm = $('#form');
    
        if(! $myForm[0].checkValidity()){
    +      e.preventDefault();
           $myForm[0].reportValidity()
        }
     }
    

    In your form you should assign a ref to it and use that instead of jQuery:

    - <Form id="form">
    + <Form ref={form => this.form = form}>
    

    and in send you can do this.form.current.checkValidity()

    This is all assuming you are using a class component. In function component you don't have access to ref but you can use the useRef hook to create refs.


    I would refactor this component, and add disabled={!this.state.isFormValid} to the Button component. You can create a function that updates this.state.isFormValid whenever any fields in the form changes.

    here's an example of how that might work https://codesandbox.io/embed/lingering-snowflake-p483o