Validate input with a component's validate()
A component that edits a value can validate it. Define self.validate(value) and return true (or an empty string) when the value is valid, or false (or a message) when it is not. Write the value back with self.modify(value): it also marks the component as modified and touched.
jComponent keeps these states in config (invalid, touched, modified) and as CSS classes (ui-invalid, ui-touched, ui-modified), so styling needs no code. ERRORS(path, callback) returns the invalid components below a path, which is what a form needs before it submits, and RESET(path) clears the touched and modified states.
<!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> Try it in your browser
Edit the example and run it. It runs in an isolated frame in your browser; nothing is sent to our server.
Preview