chainlist / svelte-forms

Svelte forms validation made easy
MIT License
403 stars 35 forks source link

How to modify input value before valiationOnChange? #96

Closed dehbini closed 1 year ago

dehbini commented 1 year ago

Hello, I have an input that get the user's mobile number, I want to change the value of mobile before it's validated on change. For example if the user's keyboard is in Arabic, I want to convert what user is typing to English.

<input type="tel" name="mobile" id="mobile" placeholder="09xxxxx xx xx" bind:value={$mobile.value} />

I already tried below code, this will update the value (the value shows in English chars), but $mobile.valid is still false. It seems that the update of the value happens after the validation. Any idea how to solve this issue?

const mobile = field('mobile', '', [required(), pattern(/^09\d{9}$/)]);
mobile.subscribe((data) => {
  data.value = convertNumberToEnglish(data.value);
});
dehbini commented 1 year ago

That was my fault. I solve the issue by breaking bind:value.

<input type="tel" name="mobile" id="mobile" placeholder="09xxxxx xx xx" value={$mobile.value} on:input={transformMobile} />
const transformMobile = (event: InputEvent) => {
    const input = event.target as HTMLInputElement;
    $mobile.value = convertNumberToEnglish(input.value);
};