phpgt/domvalidation

使用网络标准进行服务器端表单验证。

资助包维护!
PhpGt

v1.0.1 2023-03-02 14:56 UTC

README

HTML表单可以被注释,以便单独的输入元素可以描述自己的验证规则。最简单的注释是required属性,可以在输入元素上指定,以指示表单必须在提供值之前提交。

此存储库为具有服务器端DOM的项目执行W3C表单验证,例如WebEngine应用程序内的DOM

Build status Code quality Code coverage Current version PHP.Gt/DomValidation documentation

示例用法

<form id="example-form" method="post">
	<label>
		<span>Your name</span>
		<input name="name" required />
	</label>
	<label>
		<span>Your email</span>
		<input name="email" type="email" required />
	</label>
	<label>
		<span>Your account ID</span>
		<input name="account" pattern="\S*\d{,3}" />
	</label>
	<label>
		<span>Your nation</span>
		<select name="nation" required>
			<option></option>
			<option>Oceania</option>
			<option>Eurasia</option>
			<option>Eastasia</option>
		</select>
	</label>
	<button>Submit</button>
</form>

上述HTML将像往常一样在客户端进行验证,但使用下面的PHP代码将提供服务器端验证,而无需编写任何额外的验证逻辑。

上述HTML表单中存在的验证规则

  • name输入必须不为空。
  • email输入必须不为空,并且必须是有效的电子邮件地址。
  • account输入不是必需的,但在提交值时,它必须匹配提供的正则表达式(任意数量的非空白字符后跟最多3个数字)。
  • nation输入必须是<select>元素中存在的三个枚举值之一。
use Gt\Dom\HTMLDocument;
use Gt\DomValidation\Validator;
use Gt\DomValidation\ValidationException;

// Assume this function is triggered when POST data arrives.
function handleSubmit($inputData) {
	$document = new HTMLDocument(file_get_contents("example-form.html"));
// First, obtain a reference to the form we wish to validate.
	$form = $document->querySelector("#example-form");
	$validator = new Validator();

	try {
// Within a try/catch, pass the form and the user input into the Validator.
		$validator->validate($form, $inputData);
	}
	catch(ValidationException) {
// If there are any validation errors, we can iterate over them to display
// to the page, and return early as to not action the user input.
		foreach($validator->getLastErrorList() as $name => $message) {
// Here we can add an attribute to the parent of the input, for displaying
// the error message using CSS, for example.
			$errorElement = $form->querySelector("[name=$name]");
			$errorElement->parentNode->dataset->validationError = $message;
		}
        
// Return early so user input isn't used when there are validation errors. 
		return;
	}

// Finally, if the input contains no validation errors, continue as usual.
	sendInputToDatabase($inputData);
}

支持的验证机制

可以通过扩展FormValidator类并重写必要的函数来添加自己的验证机制。

  • required - 字段不能为空
  • pattern - 必须匹配提供的正则表达式
  • type - 必须匹配提供的内置数据类型
  • min - 对于数值输入,允许的最小值
  • max - 对于数值输入,允许的最大值
  • minlength - 允许的最小字符数
  • maxlength - 允许的最大字符数
  • step - 所需的粒度

支持的数据类型

  • tel
  • url
  • email
  • date
  • month
  • week
  • time
  • datetime-local
  • number
  • range

特殊元素行为

当使用<select><input type="radio" />元素时,它们包含的选项用作验证枚举,这意味着不包含在包含选项中的值将引发验证错误。