# Validare l'input con il validate() di un componente

> Implementa validate() in un componente, leggi gli stati invalid, touched e modified e trova i campi non validi con ERRORS().

Framework: jcomponent20
Product: jComponent 20 (jcomponent@20)
Language: it
Content-SHA256: 8c6c815245f5cf81d41fb3ad9957e1bc2617fd16696a77ce37e904bd1fa4e4d1
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: jcomponent20@3fedd009a277f50fddc608b97afbec553b67c51b
Review: not-recorded

Un componente che modifica un valore può validarlo. Definisci `self.validate(value)` e restituisci `true` (o una stringa vuota) quando il valore è valido, oppure `false` (o un messaggio) quando non lo è. Riscrivi il valore con `self.modify(value)`: segna anche il componente come **modified** e **touched**.

jComponent mantiene questi stati in `config` (`invalid`, `touched`, `modified`) e come classi CSS (`ui-invalid`, `ui-touched`, `ui-modified`), quindi lo stile non richiede codice. `ERRORS(path, callback)` restituisce i componenti non validi sotto un percorso, che è ciò di cui un modulo ha bisogno prima di essere inviato, e `RESET(path)` cancella gli stati touched e modified.

```html public/index.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>jComponent</title>
	<link rel="stylesheet" href="//cdn.componentator.com/spa.min@20.css" />
	<script src="//cdn.componentator.com/spa.min@20.js"></script>
</head>
<body>
	<style>.ui-invalid input { border: 2px solid crimson; }</style>

	<ui-component name="required" path="form.name"></ui-component>
	<ui-component name="required" path="form.email"></ui-component>

	<script>

		COMPONENT('required', function(self) {

			self.make = function() {
				self.html('<input type="text" />');
				self.find('input').on('input', function() {
					self.modify(this.value);
				});
			};

			self.validate = function(value) {
				return !!value && value.length > 2;
			};

			self.setter = function(value) {
				self.find('input').val(value || '');
			};
		});

		SET('form.name', 'Peter');
		SET('form.email', '');

	</script>

</body>
</html>
```
