Skip to main content

ValidationError

Struct ValidationError 

Source
pub struct ValidationError {
    pub line: usize,
    pub field: Option<String>,
    pub message: String,
}
Expand description

A problem with one row of a table. field names the column at fault when the check is specific to one, and is null for a whole-row check.

Fields§

§line: usize

The row’s one-based position in the set being validated, which is the row the editor highlights. Blank lines in the stored file are skipped on the way in, so this need not be the file line the row was read from.

§field: Option<String>§message: String

Implementations§

Source§

impl ValidationError

Source

pub fn field( line: usize, field: impl Into<String>, message: impl Into<String>, ) -> Self

A problem with the column field of the row on line.

Examples found in repository?
examples/library/main.rs (lines 256-260)
248    fn validate(&self, rows: &[Book], ctx: &Context) -> Result<Vec<ValidationError>, ApiError> {
249        let genres = Self::genres(ctx)?;
250        let branches = Self::branches(ctx)?;
251        let mut errors = Vec::new();
252
253        for (idx, row) in rows.iter().enumerate() {
254            let line = idx + 1;
255            if row.title.trim().is_empty() {
256                errors.push(ValidationError::field(
257                    line,
258                    "title",
259                    "a book needs a title",
260                ));
261            }
262
263            // A subgenre stands or falls with the genre it was chosen under.
264            if !genres.is_empty() && !row.subgenre.is_empty() {
265                let known = genres
266                    .iter()
267                    .any(|g| g.genre == row.genre && g.subgenre == row.subgenre);
268                if !known {
269                    errors.push(ValidationError::field(
270                        line,
271                        "subgenre",
272                        format!("not a subgenre of {}", row.genre),
273                    ));
274                }
275            }
276
277            if !branches.is_empty() {
278                for branch in row.shelved.keys() {
279                    if !branches.iter().any(|b| b.code == *branch) {
280                        errors.push(ValidationError::field(
281                            line,
282                            "shelved",
283                            format!("no branch has the code {branch}"),
284                        ));
285                    }
286                }
287            }
288        }
289
290        Ok(errors)
291    }
292
293    fn derive(&self, rows: &[Book], _ctx: &Context) -> Result<Vec<Value>, ApiError> {
294        Ok(rows
295            .iter()
296            .map(|row| json!({ "shelf": Self::shelf_mark(row) }))
297            .collect())
298    }
299
300    fn siblings(&self, ctx: &Context) -> Result<Value, ApiError> {
301        Ok(json!({ "genres": Self::genres(ctx)? }))
302    }
303}
304
305// ── Genres ──────────────────────────────────────────────────────────────────
306
307struct Genres;
308
309impl TableLogic for Genres {
310    type Row = Genre;
311
312    fn name(&self) -> &'static str {
313        "genres"
314    }
315
316    fn file(&self) -> &'static str {
317        GENRES_FILE
318    }
319
320    fn title(&self) -> &'static str {
321        "Genres"
322    }
323
324    fn schema(&self, _ctx: &Context) -> Result<Schema, ApiError> {
325        Ok(Schema::new([
326            Column::string("genre", "Genre").width_ch(18),
327            Column::string("subgenre", "Subgenre").width_ch(22),
328        ])
329        .sortable()
330        .new_row(
331            NewRow::new()
332                .with("genre", "")
333                .with("subgenre", "")
334                .carry_forward(["genre"]),
335        ))
336    }
337
338    fn validate(&self, rows: &[Genre], _ctx: &Context) -> Result<Vec<ValidationError>, ApiError> {
339        let mut errors = Vec::new();
340        for (idx, row) in rows.iter().enumerate() {
341            if row.genre.trim().is_empty() {
342                errors.push(ValidationError::field(
343                    idx + 1,
344                    "genre",
345                    "a genre is needed",
346                ));
347            }
348            if row.subgenre.trim().is_empty() {
349                errors.push(ValidationError::field(
350                    idx + 1,
351                    "subgenre",
352                    "a subgenre is needed",
353                ));
354            }
355        }
356        Ok(errors)
357    }
358}
359
360// ── Branches ────────────────────────────────────────────────────────────────
361
362struct Branches;
363
364impl TableLogic for Branches {
365    type Row = Branch;
366
367    fn name(&self) -> &'static str {
368        "branches"
369    }
370
371    fn file(&self) -> &'static str {
372        BRANCHES_FILE
373    }
374
375    fn title(&self) -> &'static str {
376        "Branches"
377    }
378
379    fn schema(&self, _ctx: &Context) -> Result<Schema, ApiError> {
380        // Row order here is the order the branches are listed in, which is a
381        // choice the table makes, so this table is not sortable and rows are
382        // dragged into place instead.
383        Ok(Schema::new([
384            Column::string("code", "Code").width_ch(3),
385            Column::string("name", "Name").width_ch(22),
386            Column::string("librarian_first", "Librarian").width_ch(8),
387            Column::string("librarian_last", "Surname")
388                .width_ch(8)
389                .datalist("librarian-names"),
390            Column::number("staff", "Staff").int_only().width_ch(2),
391            Column::boolean("open", "Open"),
392            Column::map(
393                "hours",
394                "Hours",
395                MapSpec::new("Day", "Hours")
396                    .key_options(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"])
397                    .value_options([
398                        SelectOption::new("09:00-17:00"),
399                        SelectOption::new("12:00-20:00"),
400                    ])
401                    .allow_new_keys()
402                    .allow_new_values(),
403            ),
404        ])
405        .datalist(
406            "librarian-names",
407            Datalist::from_rows(["librarian_last"], " "),
408        )
409        .new_row(
410            NewRow::new()
411                .with("code", "")
412                .with("name", "")
413                .with("librarian_first", "")
414                .with("librarian_last", ""),
415        ))
416    }
417
418    fn validate(&self, rows: &[Branch], _ctx: &Context) -> Result<Vec<ValidationError>, ApiError> {
419        let mut errors = Vec::new();
420        for (idx, row) in rows.iter().enumerate() {
421            if row.code.trim().is_empty() {
422                errors.push(ValidationError::field(
423                    idx + 1,
424                    "code",
425                    "a branch needs a code",
426                ));
427            }
428        }
429        Ok(errors)
430    }
Source

pub fn row(line: usize, message: impl Into<String>) -> Self

A problem with the row on line as a whole.

Trait Implementations§

Source§

impl Clone for ValidationError

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ValidationError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for ValidationError

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Eq for ValidationError

Source§

impl PartialEq for ValidationError

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for ValidationError

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for ValidationError

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.