innoweb/silverstripe-form-validation

为前端表单添加Bouncer.js表单验证。

安装: 448

依赖项: 0

建议者: 0

安全: 0

星标: 3

关注者: 3

分支: 1

开放问题: 0

语言:JavaScript

类型:silverstripe-vendormodule

2.3.0 2024-07-16 00:11 UTC

This package is auto-updated.

Last update: 2024-09-16 00:35:52 UTC


README

Version License

简介

使用Bouncer.js库为前端表单添加自动表单验证。这取代了默认的HTML5字段验证,以改善并统一浏览器中的错误消息布局。

这不会取代后端表单验证。后端验证仍应使用默认的SS验证器(例如RequiredFields)进行。

它保留UserForms表单不变,因为它们过于依赖于jQuery。

要求

  • SilverStripe ^5

注意:此版本与Silverstripe 5兼容。对于Silverstripe 4,请参阅1发布分支

安装

使用composer安装模块

composer require innoweb/silverstripe-form-validation dev-master

然后运行dev/build。

配置

无需配置。默认情况下,所有前端表单都是基于它们的HTML5属性进行验证的。

禁用验证

如果您想排除某个表单的验证,您可以在代码中禁用它

$form = Form::create($controller, 'MyForm', $fields, $actions, $validator);
$form->disableFrontendValidation();

这将在表单标签中添加类js-no-validation

要跳过特定按钮的验证,您可以添加类skip-validation到按钮。

禁用表单提交

要禁用默认的表单提交,您可以在代码中禁用它

$form = Form::create($controller, 'MyForm', $fields, $actions, $validator);
$form->disableFormSubmission();

这将在表单标签中添加类js-disable-submit

如果您想通过AJAX提交表单,这很有用。要提交表单,您可以在JavaScript中监听bouncerFormValid事件

form.addEventListener('bouncerFormValid', function (event) {
	...
}, false);

添加自定义验证器

您可以为某些字段注入自定义JavaScript验证器。为此,您需要扩展FormField如下

SilverStripe\Forms\FormField:
  extensions:
    - Your\Custom\ValidationExtension

使用addCustomValidatorScripts扩展挂钩注入您的JavaScript验证器

class ValidationExtension extends Extension
{
    // needs to be run on base FormField class, otherwise it's not going to be loaded on time
    public function addCustomValidatorScripts() {
        Requirements::javascript(
            'your/custom/field-validation.js'
        );
    }
}

在您的field-validation.js中,您需要将验证器定义添加到全局bouncerValidators变量

window.bouncerValidators = window.bouncerValidators || {};
		
window.bouncerValidators.yourCustomValidator = {
	validator: function(field) { 
		if (field.classList.contains('YourCustomField')) { // limit validator to your custom field type
			if (...) {
				// return true if field is NOT valid
				return true;
			}
		}
		// return false if field is valid!
		return false;
	},
	message: 'Please enter a valid value'
};

许可证

BSD 3-Clause许可证,请参阅许可证