如何通过Google Forms API获取表单验证规则信息?
问题:Google Forms API如何获取表单验证规则?
我正尝试以JSON格式获取Google表单数据,已获取所有问题及其类型,希望获取表单的验证规则信息。请问如何在请求中包含表单验证信息?是否可以从Google表单中获取全部验证规则?
当前使用的请求代码:
fetch(`https://forms.googleapis.com/v1/forms/${id}`, { method: 'GET', headers: { 'Authorization': `Bearer ${token}` } })
当前返回的响应示例(简化版):
{ "formId": "....", "info": { "title": "Event feedback", "description": "Thank you for participating in our event. We hope you had as much fun attending as we did organizing it.\n\nWe want to hear your feedback so we can keep improving our logistics and content. Please fill this quick survey and let us know your thoughts (your answers will be anonymous).", "documentTitle": "Event Feedback" }, "revisionId": "00000004", "responderUri": "....", "items": [ { "itemId": "....", "title": "How satisfied were you with the event?", "questionItem": { "question": { "questionId": "...", "required": true, "scaleQuestion": { "low": 1, "high": 5, "lowLabel": "Not very", "highLabel": "Very much" } } } }, { "itemId": "....", "title": "How relevant and helpful do you think it was for your job?", "questionItem": { "question": { "questionId": "....", "required": true, "scaleQuestion": { "low": 1, "high": 5, "lowLabel": "Not very", "highLabel": "Very much" } } } }, { "itemId": "....", "questionGroupItem": { "questions": [ { "questionId": "....", "required": true, "rowQuestion": { "title": "Accommodation" } } ] } } ] }
解答
1. 调整请求参数获取验证信息
默认的GET请求仅返回表单基础数据,要获取验证规则,需通过fields参数指定返回字段。最简单的方式是用*获取所有字段:
fetch(`https://forms.googleapis.com/v1/forms/${id}?fields=*`, { method: 'GET', headers: { 'Authorization': `Bearer ${token}` } })
如果需要精准控制返回字段(比如只取文本问题的验证规则),可以指定具体路径:
fetch(`https://forms.googleapis.com/v1/forms/${id}?fields=items(questionItem(question(textQuestion(validation))))`, { method: 'GET', headers: { 'Authorization': `Bearer ${token}` } })
2. 可获取的验证规则类型
不同问题类型的验证规则会嵌套在对应的问题字段下:
- 文本问题:验证规则在
textQuestion.validation中,包含字符长度限制、正则匹配、格式要求(邮箱/网址等) - 数字问题:验证规则在
numberQuestion.validation中,包含数值范围、小数权限等 - 日期/时间问题:验证规则在
dateQuestion.validation或timeQuestion.validation中,包含日期范围限制 - 注意:你当前响应中的
required字段本身就是基础验证规则,API默认会返回
3. 是否能获取全部验证规则
Google Forms API支持返回表单编辑器中设置的所有自定义验证规则,只要请求中正确指定了对应字段。如果某些规则未返回,检查是否字段路径有误,或者该类型验证暂未被API覆盖(主流验证规则均已支持)。
内容的提问来源于stack exchange,提问作者abhijith v
相关产品推荐
相关产品推荐

