htmx icon indicating copy to clipboard operation
htmx copied to clipboard

Problems with validation of elements in the form

Open benrojas01 opened this issue 1 year ago • 12 comments

Please can you tell me the correct way to validate the elements of a form, since when sending the post it makes the exchange regardless of whether the fields are empty and with the required property

thanks

benrojas01 avatar Mar 04 '24 01:03 benrojas01

@benrojas01 Can you please post your code here ?

alexandre-dos-reis avatar Mar 10 '24 06:03 alexandre-dos-reis

Could hx-validate solve your usecase here?

Telroshan avatar Mar 17 '24 19:03 Telroshan

Having this issue too.

An example form input and submit button might be.

<input type="email" class="form-control" name="email" autocomplete="off" 
  hx-validate="true" value="{{person.email}}" >
<button type="button" class="btn btn-primary"
   hx-post="/person/{{person.id}}"
   hx-target="#personCard"
   hx-indicator="#working-icon"
>Save</button>

The above fails to validate that the input is a valid email address, which the type enforces. If you do a normal submit button validation occurs and the user is informed of the failure and the submit is not done.

<button type="submit" class="btn btn-primary" >Add Person</button>

Iamrodos avatar Jun 24 '24 22:06 Iamrodos

Could hx-validate solve your usecase here?

My suspicion is this only works when the htmx action is on that input, not some other button on the form which captures and sends the inputs.

Iamrodos avatar Jun 24 '24 22:06 Iamrodos

Found a resolution for this from https://www.reddit.com/r/htmx/comments/182y0z3/htmx_client_validation/. The htmx needs to go on the form not on the button. When done this way the validations are enforced. Here is a working example.

<form 
  hx-post="/person/{{person.id}}"
  hx-target="#personCard"
  hx-indicator="#working-icon"
 >
<input type="hidden" name="csrf" value="{{user['csrf']}}">
<input type="email" class="form-control" name="email" autocomplete="off"  value="{{person.email}}" >
<div class="text-end">
   <button type="post" class="btn btn-primary" >Save</button>
</div>
</form>

Iamrodos avatar Jun 24 '24 22:06 Iamrodos