cleave.js icon indicating copy to clipboard operation
cleave.js copied to clipboard

Cleave.js bypasses input length validations

Open MatheusRich opened this issue 4 years ago • 3 comments

When using cleave.js it seems to bypass HTML validations. Codepen: https://codepen.io/matheusrich/pen/qBdmmWa

In this simple example event with minlength setted to 20, just typing a single character enables form submission. If you remove all the content from the JS tab it does not happen.

Is this intentional? How can I prevent the form submission with invalid inputs?

MatheusRich avatar Feb 27 '20 20:02 MatheusRich

Seeing the same issue. Currently working around it with Cleave's onValueChanged option and manually setting the field to invalid if necessary with setCustomValidity()

alexford avatar Mar 20 '20 11:03 alexford

My workaround was using the pattern attribute. Something like:

<input pattern=".{3}" required title="Input should be 3 characters long" />

MatheusRich avatar Mar 20 '20 22:03 MatheusRich

pattern didn't work for me. maybe my pattern is incorrect, but i wanted one for "$100,000" currency format

pattern="[$][0-9,]+"

anyway, i used alexford's method

example for anyone running into this issue, and want a quick fix without having to read/search MDN

  let options = {
    numeral: true,
    numeralPositiveOnly: true,
    swapHiddenInput: true,
    rawValueTrimPrefix: true,
    prefix: '$',
    numericOnly: true,
    numeralDecimalScale: 0,
  };

  let cleave;
  if (element.attributes.required){
    options.onValueChanged = function (e){
      console.log(e)
      if(e?.target?.rawValue == ""){
        cleave.element.setCustomValidity("Invalid field.");
      }
    }
  }

  cleave = new Cleave(element, options);

boxxxie avatar Jun 03 '21 00:06 boxxxie