Skip to main content English Español Claro Oscuro Sistema

Input

<gstock-input> | GstockInput

Ejemplos

Tamaño

Utilice el atributo de size para cambiar el tamaño del componente.

<gstock-input placeholder="Small" size="small"></gstock-input>
<gstock-input placeholder="Medium" size="medium"></gstock-input>
<gstock-input placeholder="Large" size="large"></gstock-input>

Marcador de posición

Utilice el atributo placeholder para agregar un marcador de posición.

<gstock-input placeholder="This is a placeholder..."></gstock-input>

Deshabilitado

Utilice el atributo disabled para deshabilitar el componente.

<gstock-input disabled value="This input is disabled"></gstock-input>

Solo lectura

Utilice el atributo readonly para permitir leer el valor y no modificarlo.

<gstock-input readonly="readonly" value="This value is read only"></gstock-input>

Etiqueta y texto de ayuda

Utilice los atributos label y help-text para hacer el input más accesible.

<gstock-input label="Label:" help-text="This is a test help-text."></gstock-input>

Para etiquetas y textos de ayuda personalizados con HTML, utilice los slots label y help-text.

Custom help-text with a link .
<gstock-input>
  <label slot="label" class="input-custom-label">
    <gstock-icon name="edit" size="small"></gstock-icon>
    Custom label:
  </label>
  <span slot="help-text">
    Custom help-text with a
    <a href="#label-and-help-text">link</a>
    .
  </span>
</gstock-input>

<style>
  .input-custom-label {
    display: inline-flex;
    gap: 4px;
  }
</style>

Borrar contenido

Utilice el atributo clearable para agregar un botón de limpiar cuando el input tenga contenido.

<gstock-input clearable value="Press clear button"></gstock-input>

Prefijo y sufijo

Utilice los atributos prefix y suffix para agregar iconos.

<gstock-input placeholder="Small" size="small" prefix="user" suffix="star"></gstock-input>
<gstock-input placeholder="Medium" size="medium" prefix="user" suffix="star"></gstock-input>
<gstock-input placeholder="Large" size="large" prefix="user" suffix="star"></gstock-input>

Para prefijos y sufijos personalizados con HTML, utilice los slots prefix y suffix.

<gstock-input placeholder="Small" size="small">
  <gstock-icon-button icon="user" slot="prefix" onclick="alert('clicked prefix!')"></gstock-icon-button>
  <gstock-icon-button icon="star" slot="suffix" onclick="alert('clicked suffix!')"></gstock-icon-button>
</gstock-input>

<gstock-input placeholder="Medium" size="medium">
  <gstock-icon-button icon="user" slot="prefix" onclick="alert('clicked prefix!')"></gstock-icon-button>
  <gstock-icon-button icon="star" slot="suffix" onclick="alert('clicked suffix!')"></gstock-icon-button>
</gstock-input>

<gstock-input placeholder="Large" size="large">
  <gstock-icon-button icon="user" slot="prefix" onclick="alert('clicked prefix!')"></gstock-icon-button>
  <gstock-icon-button icon="star" slot="suffix" onclick="alert('clicked suffix!')"></gstock-icon-button>
</gstock-input>

<gstock-input placeholder="Buscar por nombre, código o proveedor…" clearable>
  <gstock-icon slot="prefix" name="search"></gstock-icon>
</gstock-input>

Tipos de entrada

El atributo type controla el tipo de entrada que renderiza el navegador.



<gstock-input type="email" placeholder="Email"></gstock-input>
<br>
<gstock-input type="number" placeholder="Number"></gstock-input>
<br>
<gstock-input type="date" placeholder="Date"></gstock-input>

Mostrar/ocultar contraseña

Utilice el atributo password-toggle para agregar un botón cuando el input sea de tipo password.

<gstock-input password-toggle type="password" size="medium"></gstock-input>

Control de formulario

Este componente funciona con elementos estándar <form>. Consulta la sección sobre controles de formulario para obtener más información sobre el envío de formularios y la validación del lado del cliente.

Campo obligatorio

Utilice el atributo required para que el valor del componente sea obligatorio.


Submit Reset
<form class="input-validation-required">
  <gstock-input label="Required field:" name="test" help-text="The form will not be submitted if a required field is incomplete." required></gstock-input>
  <br>
  <gstock-button size="small" type="submit">Submit</gstock-button>
  <gstock-button size="small" variant="outlined" type="reset">Reset</gstock-button>
</form>

<script type="module">
  const form = document.querySelector('.input-validation-required');

  // Wait for controls to be defined before attaching form listeners
  await Promise.all([
    customElements.whenDefined('gstock-button'),
    customElements.whenDefined('gstock-input'),
  ]).then(() => {
    form.addEventListener('submit', event => {
      event.preventDefault();
      const formData = JSON.stringify(Object.fromEntries(new FormData(form)));
      alert(`The field is valid!\n\n${formData}`);
    });
  });
</script>

Patrón de validación

Utilice el atributo pattern para restringir un valor a un patrón específico.


Submit Reset
<form class="input-validation-pattern">
  <gstock-input name="test" label="Only letters are allowed:" pattern="[A-Za-z]+" required help-text="This example only
    allows the letters A-Z, so the form will not submit if a number or symbol is entered."></gstock-input>
  <br>
  <gstock-button size="small" type="submit">Submit</gstock-button>
  <gstock-button size="small" variant="outlined" type="reset">Reset</gstock-button>
</form>

<script type="module">
  const form = document.querySelector('.input-validation-pattern');

  // Wait for controls to be defined before attaching form listeners
  await Promise.all([
    customElements.whenDefined('gstock-button'),
    customElements.whenDefined('gstock-input'),
  ]).then(() => {
    form.addEventListener('submit', event => {
      event.preventDefault();
      const formData = JSON.stringify(Object.fromEntries(new FormData(form)));
      alert(`The field is valid!\n\n${formData}`);
    });
  });
</script>

Tipos de entrada semánticos

Algunos tipos de entrada activarán automáticamente restricciones, como email y url.



Submit Reset
<form class="input-validation-type">
  <gstock-input name="email" type="email" label="Email:" placeholder="username@example.com" required></gstock-input>
  <br>
  <gstock-input name="url" type="url" label="URL:" placeholder="https://example.com/" required></gstock-input>
  <br>
  <gstock-button size="small" type="submit">Submit</gstock-button>
  <gstock-button size="small" variant="outlined" type="reset">Reset</gstock-button>
</form>

<script type="module">
  const form = document.querySelector('.input-validation-type');

  // Wait for controls to be defined before attaching form listeners
  await Promise.all([
    customElements.whenDefined('gstock-button'),
    customElements.whenDefined('gstock-input'),
  ]).then(() => {
    form.addEventListener('submit', event => {
      event.preventDefault();
      const formData = JSON.stringify(Object.fromEntries(new FormData(form)));
      alert(`The field is valid!\n\n${formData}`);
    });
  });
</script>

Mensajes de error personalizados

Para crear un error de validación personalizado, pase una cadena no vacía al método setCustomValidity(). Esto anulará cualquier restricción de validación existente. Para hacer que el input sea válido nuevamente, llame a setCustomValidity() otra vez con una cadena vacía.


Submit Reset
<form class="input-validation-custom">
  <gstock-input name="name" label="Type `gstock` to make the input valid:" required help-text="The form will not be submitted when a custom validity is set and the browser will show a
    validation error when the containing form is submitted."></gstock-input>
  <br>
  <gstock-button size="small" type="submit">Submit</gstock-button>
  <gstock-button size="small" variant="outlined" type="reset">Reset</gstock-button>
</form>

<script type="module">
  const form = document.querySelector('.input-validation-custom');
  const input = form.querySelector('gstock-input');

  // Wait for controls to be defined before attaching form listeners
  await Promise.all([
    customElements.whenDefined('gstock-button'),
    customElements.whenDefined('gstock-input'),
  ]).then(() => {
    form.addEventListener('submit', event => {
      event.preventDefault();
      const formData = JSON.stringify(Object.fromEntries(new FormData(form)));
      alert(`The field is valid!\n\n${formData}`);
    });

    input.addEventListener('gstock-input-event', () => {
      if (input.value === 'gstock') {
        input.setCustomValidity('');
      } else {
        input.setCustomValidity("You must type 'gstock' before sending!");
      }
    });
  });
</script>

Estilos de validación

Utilice el atributo validity-styles para aplicar estilos de validación. Estos estilos se aplican solo después de una interacción del usuario, como escribir o enviar el formulario.


Submit Reset
<form class="validity-styles">
  <gstock-input name="name" label="Name:" help-text="This field is required." autocomplete="off" required validity-styles></gstock-input>
  <br>
  <gstock-button size="small" type="submit">Submit</gstock-button>
  <gstock-button size="small" variant="outlined" type="reset">Reset</gstock-button>
</form>

<script type="module">
  const form = document.querySelector('.validity-styles');

  // Wait for controls to be defined before attaching form listeners
  await Promise.all([
    customElements.whenDefined('gstock-button'),
    customElements.whenDefined('gstock-input'),
  ]).then(() => {
    form.addEventListener('submit', event => {
      event.preventDefault();
      const formData = JSON.stringify(Object.fromEntries(new FormData(form)));
      alert(`The field is valid!\n\n${formData}`);
    });
  });
</script>

Validación en línea

Para deshabilitar los mensajes de error del navegador, debe cancelar el evento gstock-invalid-event. Luego puede aplicar sus propios errores de validación en línea.



Submit Reset
<form class="inline-validation">
  <gstock-input name="name" label="Name:" help-text="This field is required." autocomplete="off" required validity-styles></gstock-input>
  <br>
  <div id="error-message" aria-live="polite" hidden></div>
  <br>
  <gstock-button size="small" type="submit">Submit</gstock-button>
  <gstock-button size="small" variant="outlined" type="reset">Reset</gstock-button>
</form>

<script type="module">
  const form = document.querySelector('.inline-validation');
  const errorMessage = document.querySelector('#error-message');

  // Wait for controls to be defined before attaching form listeners
  await Promise.all([
    customElements.whenDefined('gstock-button'),
    customElements.whenDefined('gstock-input'),
  ]).then(() => {
    form.addEventListener(
      'gstock-invalid-event',
      event => {
        event.preventDefault();
        errorMessage.textContent = `Error: ${event.target.validationMessage}`;
        errorMessage.hidden = false;
        event.target.focus();
      },
      { capture: true },
    );

    form.addEventListener('submit', event => {
      event.preventDefault();
      errorMessage.hidden = true;
      errorMessage.textContent = '';

      setTimeout(() => {
        const formData = JSON.stringify(Object.fromEntries(new FormData(form)));
        alert(`The field is valid!\n\n${formData}`);
      }, 50);
    });

    form.addEventListener('reset', () => {
      errorMessage.hidden = true;
      errorMessage.textContent = '';
    });
  });
</script>