Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

787
Vistas
Regex which validate specific positive number values only

I want to validate numbers in an input in Javascript.

The input should accept:

empty input ''
positive number '123'
decimal number '23.89' '23.88888' '.89'

But it shouldn't accept negative numbers and also '0.-99' I have used this regex:

pattern="/[+]?[0-9]+\.?[^-]?[0-9]*/";

But it accepts 0.-99 . What is the correct regex to not accept .-99

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Try this:

/^([.\d][\d]*\.?[\d]+)/g

/         
^       beginning of the input
(       
[.\d]  starting charater of the input should be either a '.', or a digit
[\d]+  then any number of digits after the first character
\.?    matches the decimal '.', ? indicates that it is optional
[\d]+  matches digits after the decimal position
)
/
g      js re global flag

Test this regex here: https://regex101.com/r/c5ELUl/1

about 4 years ago · Juan Pablo Isaza Denunciar

0

The next provided example code features both, a final validation and an immediate input value sanitizing. Both tasks are regex based.

The former covers the OP's acceptance criteria ... the pattern is as follows ... /^(?<=-*)\+?\d*\.?\d+$|^(?<=-*)\+?\d+\.$/.

The latter restricts user input while typing continues or copy-paste happens ... the pattern is based on the above, more strict, pure validation ... /^(?<=-*)(?<sign>\+?)(?<integer>\d*)(?<point>\.?)(?<float>\d*)/.

function isValidNumberValue(value) {
  value = String(value);

  return (
    (value === '') ||
    (/^(?<=-*)\+?\d*\.?\d+$|^(?<=-*)\+?\d+\.$/).test(value)
    // see ... [https://regex101.com/r/ddMyLD/4]

    //(/^(?<=-*)\+?\d*\.?\d+$/).test(value)
    // // see ... [https://regex101.com/r/ddMyLD/2]    
  );
}

function validateNumberValue({ currentTarget }) {
  currentTarget.classList.toggle('invalid', !isValidNumberValue(currentTarget.value));
}
function resetValidation({ currentTarget }) {
  currentTarget.classList.remove('invalid');
}

function sanitizeImmediately({ currentTarget }) {
  let { value } = currentTarget;
  value = value.trim();

  const {
    sign = '', integer = '', point = '', float = ''
  } = (/^(?<=-*)(?<sign>\+?)(?<integer>\d*)(?<point>\.?)(?<float>\d*)/)
    // see ... [https://regex101.com/r/ddMyLD/1]
    .exec(
      currentTarget.value.trim()
    )
    ?.groups ?? {};

  currentTarget.value = [sign, integer, point, float].join('');
}

function init() {
  const control = document.querySelector('[type="text"]');

  control.addEventListener('input', sanitizeImmediately);
  control.addEventListener('focusin', resetValidation);
  control.addEventListener('focusout', validateNumberValue);
}
init();

console.log(
  "isValidNumberValue('') ?..",
  isValidNumberValue('')
);
console.log(
  "isValidNumberValue('  ') ?..",
  isValidNumberValue('  ')
);
console.log(
  "isValidNumberValue('-0') ?..",
  isValidNumberValue('-0')
);
console.log(
  "isValidNumberValue('0') ?..",
  isValidNumberValue('0')
);
console.log(
  "isValidNumberValue(.45) ?..",
  isValidNumberValue(.45)
);
console.log(
  "isValidNumberValue(-.45) ?..",
  isValidNumberValue(-.45)
);
console.log(
  "isValidNumberValue('.-45') ?..",
  isValidNumberValue('.-45')
);
console.log(
  "isValidNumberValue(99.432) ?..",
  isValidNumberValue(99.432)
);
console.log(
  "isValidNumberValue('+9.43') ?..",
  isValidNumberValue('+9.43')
);
console.log(
  "isValidNumberValue('+9.43.45') ?..",
  isValidNumberValue('+9.43.45')
);
console.log(
  "isValidNumberValue('5.') ?..",
  isValidNumberValue('5.')
);
console.log(
  "isValidNumberValue('.') ?..",
  isValidNumberValue('.')
);
body { margin: 0; }
[type="text"].invalid { border-color: #b00; background-color: #fddddd; }
.as-console-wrapper { min-height: 88%!important; }
<input type="text" maxlength="16" />

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda