DEV Community

Narongdej Sarnsuwan
Narongdej Sarnsuwan

Posted on • Originally published at narongdej.dev on

Force input validation in Svelte

Svelte! Yet again another new Javascript Framework. Now without virtual dom that React introduce, we go back to a more jQuery style of actual DOM manipulation but still having all that (good?) stuff from React and Vue such as reactivity.

The website that you will create will likely include a web form. Where the value that the user input needs to be validated somehow. If you search google then you’ll likely come across this repl.

It all good and stuff, but what about when you want to reset the validation? For example, when the user submitted a form that locates inside a dialog. When the user presses a button to open that form again, you wouldn’t want those fields to already been validated.

Here how you can modify the code a bit to allow that

In validation.js

import { writable } from "svelte/store"
import { buildValidator } from "./validate"

export function createFieldValidator (...validators) {
  const { subscribe, set } = writable({ dirty: false, valid: false, message: null })
  const validator = buildValidator(validators)

  function action (node, binding) {
    function validate (value, dirty) {
      const result = validator(value, dirty)
      set(result)
    }

    validate(binding, false)

    return {
      update (value) {
        validate(value, true)
      }
    }
  }

  function reset() {
    setTimeout(() => {
      set({ dirty: false, valid: false, message: null })
    }, 500);
  }

  return [{ subscribe }, action, reset]
}
Enter fullscreen mode Exit fullscreen mode

Now you can call resetValidation() to reset the validation to false. For example

const [validity, validate, resetValidation] = createFieldValidator(requiredValidator(), emailValidator())

resetValidation() // <-- call this to reset the validation
Enter fullscreen mode Exit fullscreen mode

Here’s the repl

Top comments (1)

Collapse
 
roblevintennis profile image
Rob Levin

I wonder if you could achieve this with reactive statements πŸ€”