hyperstack-org / hyperstack-org/hyperstack

ActiveModel validators on the client

Offen
#297 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen
Vorherrschende Sprache
JavaScript
Sterne
538
Forks
41
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

ActiveModel provides a standard way to validate attributes, and it would be conveniently to use it on the client. Instead of validating a full record we can validate single attributes using validators directly:

```
def validate_attribute attr
value = send attr
self.class.validators_on(attr).each do |validator|
validator.validate_each(self, attr, value)
end
errors[attr].empty? ? nil : errors[attr]
end
```

And then validate user input in forms via existing model validators, something like that:
```
before_mount do
@user = User.new
end

render do
# Material UI
TextField(id: 'name', label: 'Name', required: true,
error: !@user.validate_attribute(:name).nil?,
helperText: @user.validate_attribute(:name)&.join("; ") || 'enter your name'
).
on(:change) do |evt|
@user.name = evt.target.value
end
end
```

Currently the model validators work only on the server, and aren't visible on the client, i.e. validators_on(attr) returns nil on the client. Is there some simple way to get it on the client too?

Beitragsleitfaden

Beitragsleitfaden öffnen

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.