Form Validation
Form Validation
Building on the minimal app from Quick Start, this page shows how to add powerful form validation to your GMSSH Python SDK app.
Form validation features
- Powerful validation based on
WTForms - Native lightweight form system (2.1.7+)
- Localized error messages
- Custom validator extensions
Basic Form Validation
Add form validation to the basic app from Quick Start:
# main.py
import asyncio
from simplejrpc.app import ServerApplication
from simplejrpc.response import jsonify
from simplejrpc import StringField, RequireValidator
# Create the app instance
app = ServerApplication("app.socket")
class EchoForm(BaseForm):
message = StringField(
validators=[RequireValidator(message="消息内容不能为空")]
)
@app.route(name="echo", form=EchoForm)
async def echo(message: str,lang: str):
"""Echo endpoint with validation"""
return jsonify(
data=f"收到消息: {message}",
msg="消息已处理"
)
# The original simple endpoint (no validation)
@app.route(name="hello")
async def hello():
"""Simple greeting endpoint"""
return jsonify(data="Hello, GMSSH!", msg="请求成功")
if __name__ == "__main__":
asyncio.run(app.run())Automatic validation
When form validation fails, the framework returns a standard error response automatically. You do not need to write validation logic by hand.
Custom Validators
When the built-in validators are not enough, create your own. This example adds a forbidden-word validator to the basic app:
# main.py (custom validator added to the basic version)
import asyncio
from simplejrpc import StringField, RequireValidator, Validator
from simplejrpc.app import ServerApplication
from simplejrpc.response import jsonify
from simplejrpc.exceptions import ValueError
# Create the app instance
app = ServerApplication("app.socket")
# Custom validator: forbidden-word check
class ContentFilterValidator(Validator):
def __init__(self, forbidden_words=None, message="消息包含禁用内容"):
self.forbidden_words = forbidden_words or ["spam", "广告", "违规"]
self.message = message
def validator(self, form, field):
message_lower = field.data.lower()
for word in self.forbidden_words:
if word.lower() in message_lower:
raise ValueError(f"{self.message}: 包含禁用词 '{word}'")
# Add the custom validator
class EchoForm(BaseForm):
message = StringField(validators=[RequireValidator("消息不能为空"),ContentFilterValidator(message="消息校验错误")])
# Keep the original simple endpoint
@app.route(name="echo", form=EchoForm) # version without validation
async def echo(message: str):
"""Simple echo endpoint (no validation)"""
return jsonify(
data=f"收到消息: {message}",
msg="消息已处理"
)
@app.route(name="hello")
async def hello():
"""Simple greeting endpoint"""
return jsonify(data="Hello, GMSSH!", msg="请求成功")
if __name__ == "__main__":
asyncio.run(app.run())Built-in Validators
simplejrpc ships with a rich set of built-in validators that cover most common needs:
Native Form System (Recommended)
New in v2.1.7+
Starting with 2.1.7, the SDK includes a lighter native form validation system that does not depend on WTForms and supports localized error messages.
Advantages of the Native System
- Lightweight: no external dependencies, smaller package
- Localized: built-in multilingual error messages
- Fast: a validation engine optimized for GM Desktop
- Extensible: a simple validator interface
Basic Usage
# main.py (native form system)
import asyncio
import os
from simplejrpc.app import ServerApplication
from simplejrpc import StringField, IntegerField
from simplejrpc.response import jsonify
from simplejrpc import BaseForm, RequireValidator
from simplejrpc import TextMessage
# Create the app instance
app = ServerApplication("app.socket")
# Use the native form system
class UserProfileForm(BaseForm):
username = StringField(
validators=[RequireValidator(TextMessage("USERNAME_REQUIRED"))]
)
age = IntegerField(
validators=[RequireValidator(TextMessage("AGE_REQUIRED"))]
)
@app.route(name="update_profile", form=UserProfileForm)
async def update_profile(username: str, age: int):
"""Update a user profile"""
return jsonify(
data={
"username": username,
"age": age,
"updated_at": "2024-01-01T00:00:00Z"
},
msg="用户资料更新成功"
)
@app.route(name="hello")
async def hello():
"""Simple greeting endpoint"""
return jsonify(data="Hello, GMSSH!", msg="请求成功")
if __name__ == "__main__":
asyncio.run(app.run())Field Types
| Field type | Description | Validation rule |
|---|---|---|
StringField | String field | Must be a string and must not be empty |
IntegerField | Integer field | Must be an integer |
RequireValidator | Required rule | The field must not be empty or null |
Internationalization
The native form system supports localized error messages. Create language files:
Configuration File Examples
# zh-CN.ini (Chinese)
USERNAME_REQUIRED="用户名不能为空"
AGE_REQUIRED="年龄不能为空"
INVALID_FORMAT="格式不正确"# en-US.ini (English)
USERNAME_REQUIRED="Username is required"
AGE_REQUIRED="Age is required"
INVALID_FORMAT="Invalid format"Error Response Example
When validation fails, the system returns a standard error response:
{
"jsonrpc": "2.0",
"result": {
"code": 400,
"meta": {
"endpoint": "update_profile",
"close": 1
},
"data": null,
"msg": "用户名不能为空: username"
},
"id": 1
}Client Request Example
{
"jsonrpc": "2.0",
"method": "update_profile",
"params": {
"lang": "zh-CN",
"username": "",
"age": 25
},
"id": 1
}Best Practices
Recommendations
- Combine validators: list multiple validators in
validators=[]; they run in order. - Custom validators: wrap common validation logic in custom validators for reuse.
- Error messages: give every validator a clear message to improve the user experience.
- Pick the right version: prefer the 2.1.7+ native form system, which is lighter.
Notes
Note
If a field expects a string but receives an integer, the SDK raises an internal error. Use err_msg to customize the message for that case.
Example:
# main.py
import asyncio
from simplejrpc.app import ServerApplication
from simplejrpc.response import jsonify
from simplejrpc import StringField, RequireValidator
# Create the app instance
app = ServerApplication("app.socket")
class EchoForm(BaseForm):
message = StringField(
validators=[RequireValidator(message="消息内容不能为空")],err_msg="消息内容必须为字符串"
)
@app.route(name="echo", form=EchoForm)
async def echo(message: str,lang: str):
"""Echo endpoint with validation"""
return jsonify(
data=f"收到消息: {message}",
msg="消息已处理"
)
# The original simple endpoint (no validation)
@app.route(name="hello")
async def hello():
"""Simple greeting endpoint"""
return jsonify(data="Hello, GMSSH!", msg="请求成功")
if __name__ == "__main__":
asyncio.run(app.run())