net/http/validate
Checking form input and answering with a 400.
import net.http.validate
On this page
The functions here check one value and return true or false. Assert sends a 400 response with a JSON message when the condition does not hold; after that the handler must not write another response.
Functions
Required
func Required(value: str): boolTrue when the value is not empty; whitespace counts as a value.
import net.http
import net.http.validate
import net.router
func signup(ctx: i64):
email := http.Ctx_form(ctx, "email")
validate.Assert(ctx, validate.IsEmail(email), "invalid email")
if validate.IsEmail(email):
http.Ctx_text(ctx, "welcome")
end
end
func main:
println validate.Required(""), validate.Required(" "), validate.Required("Ali")
println validate.Length("hello", 2, 5), validate.Length("hello world", 2, 5)
println validate.IsEmail("ali@example.com"), validate.IsEmail("ali@")
println validate.Matches("09121234567", "^09[0-9]{9}$"), validate.Matches("12345", "^09[0-9]{9}$")
mut r := router.NewRouter()
router.Post(r, "/signup", signup)
mut s := http.NewServer(19625)
http.Use(s, r)
_ := http.RunBackground(s)
mut headers := http.NewHeaders()
headers.insert("Content-Type", "application/x-www-form-urlencoded")
bad := http.PostWith("http://127.0.0.1:19625/signup", "email=x", headers)
println http.Status(bad), http.Body(bad)
good := http.PostWith("http://127.0.0.1:19625/signup", "email=a%40b.ir", headers)
println http.Status(good), http.Body(good)
endOutputfalse true true
true false
true false
true false
400 {"error":"invalid email"}
200 welcome
Length
func Length(value: str, min_len: int, max_len: int): boolTrue when the number of characters is between the minimum and the maximum.
The example for this item is shown with the ones above: net-http-validate-Check.salam
IsEmail
func IsEmail(value: str): boolA very simple email check: the text has to hold an
@ and a dot. To be sure, send a confirmation email.The example for this item is shown with the ones above: net-http-validate-Check.salam
Matches
func Matches(value: str, pattern: str): boolTrue when the value matches the regular expression.
The example for this item is shown with the ones above: net-http-validate-Check.salam
Assert
func Assert(ctx: i64, ok: bool, message: str)When the condition is false, sends a 400 response with
{"error": message}.The example for this item is shown with the ones above: net-http-validate-Check.salam