Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

fix(site): username validation in forms#1851

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
oxy merged 2 commits intomainfromoxy/fe-name-validate
May 27, 2022
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletionssite/src/components/CreateUserForm/CreateUserForm.tsx
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -4,7 +4,7 @@ import { FormikContextType, FormikErrors, useFormik } from "formik"
importReactfrom"react"
import*asYupfrom"yup"
import*asTypesGenfrom"../../api/typesGenerated"
import{getFormHelpers,onChangeTrimmed}from"../../util/formUtils"
import{getFormHelpers,nameValidator,onChangeTrimmed}from"../../util/formUtils"
import{FormFooter}from"../FormFooter/FormFooter"
import{FullPageForm}from"../FullPageForm/FullPageForm"

Expand All@@ -15,7 +15,6 @@ export const Language = {
emailInvalid:"Please enter a valid email address.",
emailRequired:"Please enter an email address.",
passwordRequired:"Please enter a password.",
usernameRequired:"Please enter a username.",
createUser:"Create",
cancel:"Cancel",
}
Expand All@@ -32,7 +31,7 @@ export interface CreateUserFormProps {
constvalidationSchema=Yup.object({
email:Yup.string().trim().email(Language.emailInvalid).required(Language.emailRequired),
password:Yup.string().required(Language.passwordRequired),
username:Yup.string().required(Language.usernameRequired),
username:nameValidator(Language.usernameLabel),
})

exportconstCreateUserForm:React.FC<CreateUserFormProps>=({
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,7 +3,7 @@ import TextField from "@material-ui/core/TextField"
import{FormikContextType,FormikErrors,useFormik}from"formik"
importReactfrom"react"
import*asYupfrom"yup"
import{getFormHelpers,onChangeTrimmed}from"../../util/formUtils"
import{getFormHelpers,nameValidator,onChangeTrimmed}from"../../util/formUtils"
import{LoadingButton}from"../LoadingButton/LoadingButton"
import{Stack}from"../Stack/Stack"

Expand All@@ -22,7 +22,7 @@ export const Language = {

constvalidationSchema=Yup.object({
email:Yup.string().trim().email(Language.emailInvalid).required(Language.emailRequired),
username:Yup.string().trim(),
username:nameValidator(Language.usernameLabel),
})

exporttypeAccountFormErrors=FormikErrors<AccountFormValues>
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
import { screen, waitFor } from "@testing-library/react"
import userEvent from "@testing-library/user-event"
import React from "react"
import { reach, StringSchema } from "yup"
import * as API from "../../api/api"
import { Language as FooterLanguage } from "../../components/FormFooter/FormFooter"
import { MockTemplate, MockWorkspace } from "../../testHelpers/entities"
import { renderWithAuth } from "../../testHelpers/renderHelpers"
import { Language as FormLanguage } from "../../util/formUtils"
import CreateWorkspacePage from "./CreateWorkspacePage"
import { Language, validationSchema } from "./CreateWorkspacePageView"
import { Language } from "./CreateWorkspacePageView"

const renderCreateWorkspacePage = () => {
return renderWithAuth(<CreateWorkspacePage />, {
Expand All@@ -23,8 +23,6 @@ const fillForm = async ({ name = "example" }: { name?: string }) => {
await userEvent.click(submitButton)
}

const nameSchema = reach(validationSchema, "name") as StringSchema

describe("CreateWorkspacePage", () => {
it("renders", async () => {
renderCreateWorkspacePage()
Expand All@@ -35,7 +33,7 @@ describe("CreateWorkspacePage", () => {
it("shows validation error message", async () => {
renderCreateWorkspacePage()
await fillForm({ name: "$$$" })
const errorMessage = await screen.findByText(Language.nameMatches)
const errorMessage = await screen.findByText(FormLanguage.nameInvalidChars(Language.nameLabel))
expect(errorMessage).toBeDefined()
})

Expand All@@ -47,38 +45,4 @@ describe("CreateWorkspacePage", () => {
// Check if the request was made
await waitFor(() => expect(API.createWorkspace).toBeCalledTimes(1))
})

describe("validationSchema", () => {
it("allows a 1-letter name", () => {
const validate = () => nameSchema.validateSync("t")
expect(validate).not.toThrow()
})

it("allows a 32-letter name", () => {
const input = Array(32).fill("a").join("")
const validate = () => nameSchema.validateSync(input)
expect(validate).not.toThrow()
})

it("allows 'test-3' to be used as name", () => {
const validate = () => nameSchema.validateSync("test-3")
expect(validate).not.toThrow()
})

it("allows '3-test' to be used as a name", () => {
const validate = () => nameSchema.validateSync("3-test")
expect(validate).not.toThrow()
})

it("disallows a 33-letter name", () => {
const input = Array(33).fill("a").join("")
const validate = () => nameSchema.validateSync(input)
expect(validate).toThrow()
})

it("disallows a space", () => {
const validate = () => nameSchema.validateSync("test 3")
expect(validate).toThrow()
})
})
})
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -10,22 +10,13 @@ import { Loader } from "../../components/Loader/Loader"
import{Margins}from"../../components/Margins/Margins"
import{ParameterInput}from"../../components/ParameterInput/ParameterInput"
import{Stack}from"../../components/Stack/Stack"
import{getFormHelpers,onChangeTrimmed}from"../../util/formUtils"
import{getFormHelpers,nameValidator,onChangeTrimmed}from"../../util/formUtils"

exportconstLanguage={
templateLabel:"Template",
nameLabel:"Name",
nameRequired:"Please enter a name.",
nameMatches:"Name must start with a-Z or 0-9 and can contain a-Z, 0-9 or -",
nameMax:"Name cannot be longer than 32 characters",
}

// REMARK: Keep in sync with coderd/httpapi/httpapi.go#L40
constmaxLenName=32

// REMARK: Keep in sync with coderd/httpapi/httpapi.go#L18
constusernameRE=/^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$/

exportinterfaceCreateWorkspacePageViewProps{
loadingTemplates:boolean
loadingTemplateSchema:boolean
Expand All@@ -39,10 +30,7 @@ export interface CreateWorkspacePageViewProps {
}

exportconstvalidationSchema=Yup.object({
name:Yup.string()
.required(Language.nameRequired)
.matches(usernameRE,Language.nameMatches)
.max(maxLenName,Language.nameMax),
name:nameValidator(Language.nameLabel),
})

exportconstCreateWorkspacePageView:React.FC<CreateWorkspacePageViewProps>=(props)=>{
Expand Down
38 changes: 37 additions & 1 deletionsite/src/util/formUtils.test.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import{FormikContextType}from"formik/dist/types"
import{getFormHelpers,onChangeTrimmed}from"./formUtils"
import{getFormHelpers,nameValidator,onChangeTrimmed}from"./formUtils"

interfaceTestType{
untouchedGoodField:string
Expand DownExpand Up@@ -35,6 +35,8 @@ const form = {
},
}asunknownasFormikContextType<TestType>

constnameSchema=nameValidator("name")

describe("form util functions",()=>{
describe("getFormHelpers",()=>{
describe("without API errors",()=>{
Expand DownExpand Up@@ -94,4 +96,38 @@ describe("form util functions", () => {
expect(mockHandleChange).toHaveBeenCalledWith({target:{value:"hello"}})
})
})

describe("nameValidator",()=>{
it("allows a 1-letter name",()=>{
constvalidate=()=>nameSchema.validateSync("a")
expect(validate).not.toThrow()
})

it("allows a 32-letter name",()=>{
constinput=Array(32).fill("a").join("")
constvalidate=()=>nameSchema.validateSync(input)
expect(validate).not.toThrow()
})

it("allows 'test-3' to be used as name",()=>{
constvalidate=()=>nameSchema.validateSync("test-3")
expect(validate).not.toThrow()
})

it("allows '3-test' to be used as a name",()=>{
constvalidate=()=>nameSchema.validateSync("3-test")
expect(validate).not.toThrow()
})

it("disallows a 33-letter name",()=>{
constinput=Array(33).fill("a").join("")
constvalidate=()=>nameSchema.validateSync(input)
expect(validate).toThrow()
})

it("disallows a space",()=>{
constvalidate=()=>nameSchema.validateSync("test 3")
expect(validate).toThrow()
})
})
})
26 changes: 26 additions & 0 deletionssite/src/util/formUtils.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,18 @@
import{FormikContextType,FormikErrors,getIn}from"formik"
import{ChangeEvent,ChangeEventHandler,FocusEventHandler,ReactNode}from"react"
import*asYupfrom"yup"

exportconstLanguage={
nameRequired:(name:string):string=>{
return`Please enter a${name.toLowerCase()}.`
},
nameInvalidChars:(name:string):string=>{
return`${name} must start with a-Z or 0-9 and can contain a-Z, 0-9 or -`
},
nameTooLong:(name:string):string=>{
return`${name} cannot be longer than 32 characters`
},
}

interfaceFormHelpers{
name:string
Expand DownExpand Up@@ -38,3 +51,16 @@ export const onChangeTrimmed =
event.target.value=event.target.value.trim()
form.handleChange(event)
}

// REMARK: Keep in sync with coderd/httpapi/httpapi.go#L40
constmaxLenName=32

// REMARK: Keep in sync with coderd/httpapi/httpapi.go#L18
constusernameRE=/^[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$/

// REMARK: see #1756 for name/username semantics
exportconstnameValidator=(name:string):Yup.StringSchema=>
Yup.string()
.required(Language.nameRequired(name))
.matches(usernameRE,Language.nameInvalidChars(name))
.max(maxLenName,Language.nameTooLong(name))

[8]ページ先頭

©2009-2025 Movatter.jp