验证模糊或更少

发布于 2025-01-16 00:55:16 字数 2715 浏览 0 评论 0原文

我正在将 Vee-validate 4 与 Vue 3 一起使用。我试图验证数据库中的用户名(如果存在)。所以,这就是我的做法

字段:

<div>
                        <div class="relative border border-gray-500 rounded-md px-3 py-2 shadow-sm focus-within:ring-1 focus-within:ring-blue-600 focus-within:border-blue-600 ">
                            <label for="name" value="Name" class="absolute -top-2 left-2 -mt-px inline-block px-1 bg-gray-900 text-sm font-medium text-gray-50">Username</label>
                            <Field @keydown.space.prevent type="text" autocomplete="username" name="name" id="name" v-model="form.name" :rules="validateUsername" validateOnInput required autofocus class="bg-gray-900 text-white block w-full border-0 p-0 placeholder-gray-500 focus:ring-0 sm:text-sm" placeholder="" />
                        </div>
                        <ErrorMessage name="name" class="text-red-500 mt-2" />
                    </div>

调用数据库:

const usernameIsUnique = (name) => 
    axios.post("/api/verify/checkusername", { name })
        .then(({ data }) => data)
        .catch(err => ({ // resolve with error details
        valid: err.response?.data?.valid ?? false,
        data: {
            // get the message from the response if it exists
            message: err.response?.data?.data?.message ?? "Username already registered"
        }
    })); 

异步方法:

async validateUsername(value) {
                // if the field is empty
                if (!value) {
                    return 'This field is required';
                }
                const regex = /^[a-zA-Z0-9_.+-]{4,20}$/i;
                if (!regex.test(value)) {
                    return 'This must be a minimum of 4 characters';
                }
                const check = await usernameIsUnique(value);
                if (check.valid) {
                    return true;
                }
                // All is good
                return check.valid || check.data.message;
            },

我正在处理 2 个问题

  • 验证器在每次按键时运行。在我看来,它应该只在 Blur 上运行
  • 。验证器区分大小写。我怎样才能使其不区分大小写?

对于第二个问题,请注意我是在 Laravel 的控制器中执行此操作。所以,这是该代码。

Laravel Controller

public function checkUsername(Request $request) {
        Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:255', 'unique:users'],
        ])->validate();
    
        return response()->json([
            'valid' => true,
            'data' => [
                'message' => 'Username is available!'
            ]
        ], 200);
    }

我很困惑,所以我真的可以在这里使用一些指导。

I am using Vee-validate 4 with Vue 3. I am trying to validate a username in the database if it exists. So, this is how I do it

Field:

<div>
                        <div class="relative border border-gray-500 rounded-md px-3 py-2 shadow-sm focus-within:ring-1 focus-within:ring-blue-600 focus-within:border-blue-600 ">
                            <label for="name" value="Name" class="absolute -top-2 left-2 -mt-px inline-block px-1 bg-gray-900 text-sm font-medium text-gray-50">Username</label>
                            <Field @keydown.space.prevent type="text" autocomplete="username" name="name" id="name" v-model="form.name" :rules="validateUsername" validateOnInput required autofocus class="bg-gray-900 text-white block w-full border-0 p-0 placeholder-gray-500 focus:ring-0 sm:text-sm" placeholder="" />
                        </div>
                        <ErrorMessage name="name" class="text-red-500 mt-2" />
                    </div>

call to DB:

const usernameIsUnique = (name) => 
    axios.post("/api/verify/checkusername", { name })
        .then(({ data }) => data)
        .catch(err => ({ // resolve with error details
        valid: err.response?.data?.valid ?? false,
        data: {
            // get the message from the response if it exists
            message: err.response?.data?.data?.message ?? "Username already registered"
        }
    })); 

async method:

async validateUsername(value) {
                // if the field is empty
                if (!value) {
                    return 'This field is required';
                }
                const regex = /^[a-zA-Z0-9_.+-]{4,20}$/i;
                if (!regex.test(value)) {
                    return 'This must be a minimum of 4 characters';
                }
                const check = await usernameIsUnique(value);
                if (check.valid) {
                    return true;
                }
                // All is good
                return check.valid || check.data.message;
            },

I am dealing with 2 issues

  • The validator is running on every key press. In my head, it should only run on Blur
  • The validator is case-sensitive. How could I make it case-insensitive?

For the second issue, Note I am doing this in Laravel in a controller. So, here is that code.

Laravel Controller

public function checkUsername(Request $request) {
        Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:255', 'unique:users'],
        ])->validate();
    
        return response()->json([
            'valid' => true,
            'data' => [
                'message' => 'Username is available!'
            ]
        ], 200);
    }

I am stumped so I could really use some guidance here.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

撑一把青伞 2025-01-23 00:55:16

对于该库,似乎没有模糊方法,相反,您可以使用去抖方法

去抖本质上是在用户在一定时间后停止更改值后运行验证,在这种情况下,1秒使用 data-vv-delay="1000" 属性。

<div>
    <div class="relative border border-gray-500 rounded-md px-3 py-2 shadow-sm focus-within:ring-1 focus-within:ring-blue-600 focus-within:border-blue-600 ">
        <label for="name" value="Name" class="absolute -top-2 left-2 -mt-px inline-block px-1 bg-gray-900 text-sm font-medium text-gray-50">Username</label>
        <Field
            @keydown.space.prevent
            type="text"
            autocomplete="username"
            name="name"
            id="name"
            v-model="form.name"
            :rules="validateUsername"
            validateOnInput
            required
            autofocus
            class="bg-gray-900 text-white block w-full border-0 p-0 placeholder-gray-500 focus:ring-0 sm:text-sm"
            placeholder=""
            data-vv-delay="1000"
        />
    </div>
    <ErrorMessage name="name" class="text-red-500 mt-2" />
</div>

至于不敏感的唯一验证,您将必须创建一个新的验证器。

然而app/Providers/AppServiceProvider.php


...

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('iunique', function ($attribute, $value, $parameters, $validator) {
            $query = DB::table($parameters[0]);
            $column = $query->getGrammar()->wrap($parameters[1]);
            return ! $query->whereRaw("lower({$column}) = lower(?)", [$value])->count();
        });
    }
...

并未 100% 验证。从 github 得到这个 https://github.com/laravel/framework/issues /9430#issuecomment-274482274

With that library there does not seem to be a blur method, instead you could use a debounce method

debounce is essentially running the validation after the user has stopped changing the value after a certain amount of time in this case, 1 second using the data-vv-delay="1000" attribute.

<div>
    <div class="relative border border-gray-500 rounded-md px-3 py-2 shadow-sm focus-within:ring-1 focus-within:ring-blue-600 focus-within:border-blue-600 ">
        <label for="name" value="Name" class="absolute -top-2 left-2 -mt-px inline-block px-1 bg-gray-900 text-sm font-medium text-gray-50">Username</label>
        <Field
            @keydown.space.prevent
            type="text"
            autocomplete="username"
            name="name"
            id="name"
            v-model="form.name"
            :rules="validateUsername"
            validateOnInput
            required
            autofocus
            class="bg-gray-900 text-white block w-full border-0 p-0 placeholder-gray-500 focus:ring-0 sm:text-sm"
            placeholder=""
            data-vv-delay="1000"
        />
    </div>
    <ErrorMessage name="name" class="text-red-500 mt-2" />
</div>

as for the insensitive unique validation you will have to create a new validator.

app/Providers/AppServiceProvider.php


...

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('iunique', function ($attribute, $value, $parameters, $validator) {
            $query = DB::table($parameters[0]);
            $column = $query->getGrammar()->wrap($parameters[1]);
            return ! $query->whereRaw("lower({$column}) = lower(?)", [$value])->count();
        });
    }
...

not 100% on the validation however. got this from the github https://github.com/laravel/framework/issues/9430#issuecomment-274482274

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文