I am in need of a code to validate that in an input I only accept one word "item" + numbers, that is, I only accept those filters, and be able to send an alert to a user that enters that input.
example:
item123
I am in need of a code to validate that in an input I only accept one word "item" + numbers, that is, I only accept those filters, and be able to send an alert to a user that enters that input.
example:
item123
You must use regular expressions to be able to validate the entered text. I leave you how the javascript code would be with the validation.
function validar(evt) {
var exp = /^item\d+$/;
var nombre = document.getElementById("nombre").value;
evt.preventDefault();
if (exp.test(nombre)) {
alert("Valido");
} else {
alert("Invalido");
}
}
<!DOCTYPE html>
<html>
<head>
<title>Prueba</title>
</head>
<body>
<form id="form">
<input type="text" id="nombre">
<button onclick="validar(event)">Enviar</button>
</form>
</body>
</html>
Although your question is not well formulated, I will tell you one way to do it.
What you want to do is called text field validation to alphanumeric characters and you can use regular expressions for this, a kind of patterns to find a certain combination of characters within a text string.
Here I'll leave an example assuming you want to validate a form to send data:
var texto = document.getElementById("text").value;
var er = /[A-Za-z0-9]/;
if (er.test(text)) {
//alert("Expresion regular es aceptada");
} else {
//alert("expresion regular no aceptada");
}
<html>
<head>
<title>Expresiones regulares</title>
</head>
<body>
<form>
<input type="text" placeholder='Texto' id='text' name='text'>
<input type="submit" value="Enviar">
</form>
</body>
</html>
There you have an example of how to do it, you just have to adapt it to your needs and start to know a little more the regular expressions and how to use them, especially in JavaScript that are sometimes very necessary for the validation of forms.
If this is the answer you were looking for or is the one that most convinces you, mark it as accepted. Greetings.