Validate input by accepting specific amount of letters and numbers in javascript "for an RA, ex: p3087748"

Asked

Viewed 234 times

3

I did a validation in HTML using pattern, I tried to put letters and numbers at the same time. But I believe that there is no way to determine the minimum of letter and numbers.

Example: Only one "letter" and "seven numbers" in this sequence.

In the first moment I did so, number and letters check (if it is different from this returns an error).

function check(inputvalue) {
    let teste = /^[0-9A-Za-z]+$/;
    
    if(inputvalue.value.match(teste)) {
      alert("Sucess");
    } else {
      alert("Fail");
    }
  }
<input type="text" id="inputvalue">
<button onclick="check(inputvalue)">
 testando
</button>

1 answer

3


Of course it has how to determine specific quantities.

If you want a letter followed by 7 numbers, just change the regex to:

/^[A-Za-z][0-9]{7}$/

If you want to define the minimum and maximum quantity, just change the quantifier. For example, {2,7} for a minimum of 2 and a maximum of 7. Or {2,} at least 2, without a ceiling.


Another detail is that the method match returns an array containing various information, such as the snippet that was found, capture groups, etc. But if you don’t need this information and only want to know if the string corresponds to regex (ie only "yes or no"), you can use method test, that simply returns true or false:

let regex = /^[A-Za-z][0-9]{7}$/;
if (regex.test(inputvalue.value)) {
    // sucesso
} else {
    // falha
}

And this regex can be used in the attribute pattern hassle-free:

const campo = document.querySelector('#campo');

campo.addEventListener('input', () => {
  campo.setCustomValidity('');
  campo.checkValidity();
});

campo.addEventListener('invalid', () => {
    campo.setCustomValidity('O campo deve ter uma letra seguida de 7 dígitos');
});
/* deixar borda vermelha enquanto o campo for inválido */
input:invalid {
  border: red 1px solid;
}
<form>
  <input id="campo" type="text" pattern="^[A-Za-z][0-9]{7}$" required />
  <input type="submit" value="ok">
</form>

  • 1

    Man, I’m sorry for the mega delay! But everything went well, gave right yes ( thanks for your explanation )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.