nosir / cleave.js

Format input text content when you are typing...
http://nosir.github.io/cleave.js
Apache License 2.0
17.95k stars 1.62k forks source link

Cleave.js bypasses input length validations #562

Open MatheusRich opened 4 years ago

MatheusRich commented 4 years ago

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?

alexford commented 4 years ago

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

MatheusRich commented 4 years ago

My workaround was using the pattern attribute. Something like:

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

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);