Skip to content

Commit

Permalink
Add and display server validation error message
Browse files Browse the repository at this point in the history
  • Loading branch information
zainfathoni committed Jun 19, 2020
1 parent 51453b0 commit 662a74e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
13 changes: 13 additions & 0 deletions api/src/services/contacts/contacts.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
import { UserInputError } from '@redwoodjs/api'

import { db } from 'src/lib/db'

const validate = (input) => {
if (input.email && !input.email.match(/[^@]+@[^.]+\..+/)) {
throw new UserInputError("Can't create new contact", {
messages: {
email: ['is not formatted like an email address'],
},
})
}
}

export const contacts = () => {
return db.contact.findMany()
}

export const createContact = ({ input }) => {
validate(input)
return db.contact.create({ data: input })
}
10 changes: 8 additions & 2 deletions web/src/pages/ContactPage/ContactPage.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import BlogLayout from 'src/layouts/BlogLayout'
import {
Form,
FormError,
Label,
TextField,
TextAreaField,
Expand All @@ -21,7 +22,7 @@ const CREATE_CONTACT = gql`
const ContactPage = () => {
const formMethods = useForm()

const [create, { loading }] = useMutation(CREATE_CONTACT, {
const [create, { loading, error }] = useMutation(CREATE_CONTACT, {
onCompleted: () => {
formMethods.reset()
alert('Thank you for your message!')
Expand All @@ -39,7 +40,12 @@ const ContactPage = () => {
onSubmit={onSubmit}
validation={{ mode: 'onBlur' }}
formMethods={formMethods}
error={error}
>
<FormError
error={error}
wrapperStyle={{ color: 'red', backgroundColor: 'lavenderBlush' }}
/>
<Label errorClassName="error" name="name">
Your Name
</Label>
Expand All @@ -56,7 +62,7 @@ const ContactPage = () => {
<TextField
name="email"
errorClassName="error"
validation={{ required: true, pattern: { value: /[^@]+@[^.]+\..+/ } }}
validation={{ required: true }}
/>
<FieldError className="error" name="email" />

Expand Down

0 comments on commit 662a74e

Please sign in to comment.