|
| 1 | +import gradio as gr |
| 2 | +import modelscope_studio.components.antd as antd |
| 3 | +import modelscope_studio.components.base as ms |
| 4 | + |
| 5 | + |
| 6 | +def on_submit(_form): |
| 7 | + print(_form) # the Form Component will automatically collect the form data |
| 8 | + |
| 9 | + |
| 10 | +def bind_action_event(action): |
| 11 | + |
| 12 | + def on_action(): |
| 13 | + return gr.update(form_action=action) |
| 14 | + |
| 15 | + return on_action |
| 16 | + |
| 17 | + |
| 18 | +with gr.Blocks() as demo: |
| 19 | + with ms.Application(): |
| 20 | + with antd.ConfigProvider(): |
| 21 | + with antd.Card(title="Out of the Form"): |
| 22 | + submit_btn = antd.Button("Submit", type="primary") |
| 23 | + reset_btn = antd.Button("Reset") |
| 24 | + validate_btn = antd.Button("Validate") |
| 25 | + |
| 26 | + with antd.Form(label_col=dict(span=8), |
| 27 | + wrapper_col=dict(span=16)) as form: |
| 28 | + with antd.Form.Item( |
| 29 | + form_name="username", |
| 30 | + label="Username", |
| 31 | + rules=[{ |
| 32 | + "required": True, |
| 33 | + "message": 'Please input your username!' |
| 34 | + }, { |
| 35 | + "pattern": |
| 36 | + "^[a-zA-Z0-9]+$", |
| 37 | + "message": |
| 38 | + "Username can only contain letters and numbers!" |
| 39 | + }, { |
| 40 | + "min": |
| 41 | + 6, |
| 42 | + "message": |
| 43 | + "Username must be at least 6 characters long!" |
| 44 | + }, { |
| 45 | + "max": |
| 46 | + 20, |
| 47 | + "message": |
| 48 | + "Username must be at most 20 characters long!" |
| 49 | + }]): |
| 50 | + antd.Input() |
| 51 | + with antd.Form.Item( |
| 52 | + form_name="password", |
| 53 | + label="Password", |
| 54 | + rules=[ |
| 55 | + { |
| 56 | + "required": True, |
| 57 | + "message": 'Please input your password!' |
| 58 | + }, |
| 59 | + { |
| 60 | + # custom validator with javascript function |
| 61 | + "validator": |
| 62 | + """(rule, value, cb) => { |
| 63 | + if (value !== '123') { |
| 64 | + cb('Password must be "123"') |
| 65 | + } |
| 66 | + cb() |
| 67 | + }""" |
| 68 | + } |
| 69 | + ]): |
| 70 | + antd.Input.Password() |
| 71 | + |
| 72 | + with antd.Form.Item(wrapper_col=dict(offset=8, span=16)): |
| 73 | + antd.Button("Submit", type="primary", html_type="submit") |
| 74 | + form.finish(on_submit, inputs=[form]) |
| 75 | + submit_btn.click(bind_action_event("submit"), outputs=[form]) |
| 76 | + reset_btn.click(bind_action_event("reset"), outputs=[form]) |
| 77 | + validate_btn.click(bind_action_event("validate"), outputs=[form]) |
| 78 | + |
| 79 | +if __name__ == "__main__": |
| 80 | + demo.queue().launch() |
0 commit comments