Mazdul Prodhan
Mazdul Prodhan

Reputation: 21

How can I validate min max setting dynamic value?

when I am using exact number, its working. but when I am using dynamic value , validation not working.this is created with react-hook-form validation.

<div class="form-control">
    <label class="label">
        <span class="label-text">Quantity</span>
    </label>
    <input type="number" placeholder={minOrder} {...register("quantity", {
        required: true, max: {stock}, min: {minOrder}})} />
    <label class="label">
    {
        errors.quantity?.type === 'min' &&
            <span class="label-text-alt text-red-600 font-bold">
                You must fulfill the minimum order
            </span>
    }
    {
        errors.quantity?.type === 'max' &&
            <span class="label-text-alt text-red-600 font-bold">
                Out of Stock
            </span>
    }
    </label>
</div>

Upvotes: 1

Views: 6669

Answers (1)

Tushar
Tushar

Reputation: 41

You can create custom validation on react-hook-form by using the following example

       let minValue = 0;
       let maxValue = 200;

<div>
   <label htmlFor="parcel_value">Value*</label>
   {errors?.parcelValue?.message && (
     <span>{errors?.parcelValue?.message}</span>
   )}
   {errors?.parcelValue?.type == "positiveNumber" && (
     <span>Value At least 1$ required</span>
   )}
   {errors?.parcelValue?.type == "lessThanHundred" && (
     <span> Value should not be greater than 200</span>
  )}

  <br />
  <input id="parcel_value" type="number"
    {...register("parcelValue", {
      required: "(required)",
      validate: { positiveNumber: (value) => parseFloat(value) > minValue,
      lessThanHundred: (value) => parseFloat(value) < maxValue },
     })}
  />
</div>

source: https://codesandbox.io/s/react-hook-form-custom-validation-8kuu7

Upvotes: 3

Related Questions