it('renders validation errors', async () => { props = { ...props, name: 'number', label: 'Number' } const wrapper = mount( <Formik initialValues={{number: props.options[0].value}} validationSchema={object().shape({ number: number().positive() })} render={() => (<Form><Select {...props}/></Form>)}/>) expect(wrapper.find(ErrorMessage).text()).to.be.null // Simulate an invalid (negative) number is selected wrapper.find('select').simulate('change', {target: {id: 'number', value: -3}}) wrapper.find('form').simulate('submit') await tick() // Expect an error message to be rendered expect(wrapper.find(ErrorMessage).text()).to.be.equal('number must be a positive number') })
it('should fall back to using schema types', function() { let schema = yup.object({ string: yup.string(), number: yup.number(), date: yup.date(), bool: yup.bool(), array: yup.array().of(yup.string()), }) let wrapper = mount( <Form schema={schema} defaultValue={{}}> <Form.Field name="string" /> <Form.Field name="number" /> <Form.Field name="date" /> <Form.Field name="bool" /> <Form.Field name="array" /> </Form> ) wrapper.assertSingle(`Input[name='string']`) wrapper.assertSingle(inputs.Number) wrapper.assertSingle(inputs.Bool) wrapper.assertSingle(inputs.Select) wrapper.assertSingle(inputs.Date) })
renderForm() { let event = this.props.event const people = this.props.listContainer.people.edges const host = (people.length === 0) ? null : people[0].node const eventSchema = yup.object({ name: yup .string() .default(event.name) .required(), eventTypeId: yup .string() .default(event.eventType.id) .required(), description: yup.string().default(event.description) .required(), rsvpEmailReminderHours: yup.number() .default(event.rsvpEmailReminderHours) .min(0) .nullable(), startDate: yup.date() .default(momentWithOffset(event.startDate, event.localUTCOffset).toDate()) .required(), localTimezone: yup.string() .default(event.localTimezone) .required(), duration: yup.object({ h: yup.number() .default(Math.floor(event.duration / 60)) .min(-1) .nullable() .required(), m: yup.number() .default(event.duration % 60) .min(-1).max(59) .nullable() .required(), }), venueName: yup.string().default(event.venueName) .required(), venueAddr1: yup.string().default(event.venueAddr1) .required(), venueAddr2: yup.string().default(event.venueAddr2) .nullable(), venueCity: yup.string().default(event.venueCity) .required(), venueState: yup.string().default(event.venueState) .required(), venueZip: yup.string().default(event.venueZip) .required(), venueCountry: yup.string().default(event.venueCountry) .required(), venueDirections: yup.string().default(event.venueDirections) .nullable(), capacity: yup.number() .default(event.capacity) .min(0) .required(), hostEmail: yup.string().email() .default((event.host) ? event.host.email : null), contactPhone: yup.string() .default(event.contactPhone), publicPhone: yup.boolean() .default(event.publicPhone), hostReceiveRsvpEmails: yup.boolean() .default(event.hostReceiveRsvpEmails), rsvpUseReminderEmail: yup.boolean() .default(event.rsvpUseReminderEmail), attendeeVolunteerShow: yup.string() .default(String(event.attendeeVolunteerShow)), attendeeVolunteerMessage: yup.string() .default(event.attendeeVolunteerMessage), isSearchable: yup.string() .default(String(event.isSearchable)), isOfficial: yup.boolean() .default(event.isOfficial) }); const form = ( <GCForm ref="form" schema={eventSchema} defaultValue={eventSchema.default()} onSubmit={ (data) => { data.description = this.refs.quill.getEditorContents(); data.duration = data.duration.h * 60 + data.duration.m; data.isSearchable = Number(data.isSearchable); if (host) data.hostId = host.id delete data.hostEmail this.props.onSubmit(data) }} > <InfoHeader content='Event Information' /> <Form.Field name='eventTypeId' type='select' label='Event Type' fullWidth={true} choices={this.eventTypes()} /> <br /> <Form.Field name='name' label='Event Name' fullWidth={true} /> <br /><br /> <label>Event Description</label> <ReactQuill defaultValue={event.description} theme="snow" ref="quill" /> <InfoHeader content='Event Date & Time' /> <Form.Field name='startDate' label='Start Date/Time' type='datetime' utcOffset={event.localUTCOffset} /> <Form.Field name='localTimezone' type='select' label='Time Zone' choices={this.timezones()} style={{ marginTop: 5 }} /><br/> <Form.Field name='duration.h' label="Duration (Hours)" type='number' min="0" /> <Form.Field name='duration.m' label="Duration (Minutes)" type='number' min="0" max="59" /> <InfoHeader content='Event Location' /> <Form.Field name='venueName' label='Venue Name' /> <Form.Field name='capacity' label="Venue Capacity (enter 0 for unlimited)" type='number' min="0" /><br/> <Form.Field name='venueAddr1' label='Address Line 1' fullWidth={true} /> <Form.Field name='venueAddr2' label='Address Line 2' fullWidth={true} /> <Form.Field name='venueCity' label='City' /> <Form.Field name='venueState' label='State' /> <Form.Field name='venueZip' label='Zip Code' /> <Form.Field name='venueCountry' label='Country' /> <Form.Field name='venueDirections' label='Directions to Venue' multiLine={true} fullWidth={true} /> <InfoHeader content='Event Host' /> {(host) ? `${host.firstName} ${host.lastName}` : 'No host name available'}<br /> <Form.Field name="hostEmail" type="email" label="Host Email" errorText={(host) ? null : 'No account found'} onChange={(value) => { this.props.relay.setVariables({personFilters: {email: value}}) }} /><br /> <Form.Field name="contactPhone" type="phone" label="Contact Phone" /><br/><br/> <Form.Field name="publicPhone" label="Make Contact Number Public" /><br/> <Form.Field name="hostReceiveRsvpEmails" label="Send Host RSVPs via Email" /> <InfoHeader content='Event Attendees' /> <Form.Field name="rsvpUseReminderEmail" label="Send Guests RSVP Email Reminder" /> <Form.Field name='rsvpEmailReminderHours' label="RSVP Reminder Hours" type='number' min="0" /><br/><br/> <Form.Field name="attendeeVolunteerShow" type='select' label="Ask Attendees to Volunteer" fullWidth={true} choices={this.volunteerShowOptions()} /> <Form.Field name='attendeeVolunteerMessage' label="Message for Event Volunteers" multiLine={true} fullWidth={true} /> <InfoHeader content='Event Settings' /> <Form.Field name='isSearchable' type='select' label='Make Event Public?' fullWidth={true} choices={this.eventSearchableOptions()} /> <Form.Field name="isOfficial" label="Mark as an official campaign event" /> <Form.Button style={ { display: "none" } } ref="submit" type='submit' label='Submit Changes' fullWidth={true} /> </GCForm>) return form }
const defaultStr = yup.string().default(''); const customerSchema = yup .object({ name: yup.object({ first: defaultStr .required('Please enter a first name'), last: defaultStr .required('Please enter a surname'), }), dateOfBirth: yup.date() .max(new Date(), 'Are you a time traveler?!'), colorId: yup.number() .nullable() .required('Please select a dank color'), }); const options = [ { id: 0, label: 'Red' }, { id: 1, label: 'Yellow' }, { id: 2, label: 'Blue' }, { id: 3, label: 'Other' }, ]; const FormExample = () => ( <Form defaultValue={customerSchema.default()} onSubmit={(v) => console.log(v)}
import yup from 'yup' export default yup.object({ name: yup.string().required('please enter name'), cost: yup.number().label('Cost').positive().min(1).max(10000000, 'max Cost 10000000'), percent: yup.string(), group: yup.string() });
import connection from './db' import {number, object} from 'yup' import {transformYupToFormikError} from './utils/error-transform' import {requiredMsg, numTypeMsg, atLeastNumMsg} from './utils/error-message' import {WorkoutSchema} from './workout' // A session schema const SessionSchema = object() .concat(WorkoutSchema) .shape({ roundsCompleted: number(numTypeMsg('Rounds completed')) .min(0, atLeastNumMsg('Rounds completed', 0)) .required(requiredMsg('Rounds completed')), startedAt: number(numTypeMsg('Started at')) .required(requiredMsg('Started at')), finishedAt: number(numTypeMsg('Finished at')) .required(requiredMsg('Finished at')) }) // Validate a session attributes. Return a resolved Promise with the valid attrs, a Rails-like // error object otherwise export async function validateSession(attrs) { try { const sessionAttrs = await SessionSchema.validate(attrs) return sessionAttrs } catch (yupError) { return Promise.reject(transformYupToFormikError(yupError)) } } // Return a paginated array of sessions, where newest sessions are returned first (descending order)
const { object, string, number, date } = require('yup') const contactSchema = object({ name: string() .required(), age: number() .required() .positive() .integer(), email: string() .email(), website: string() .url(), createdOn: date() .default(() => new Date()) }) contactSchema.cast({ name: 'jimmy', age: '24', createdOn: '2014-09-23T19:25:25Z' })
var _ = require('lodash') , Clank = require('clank') , Resource = require('miniature') , yup = require('yup') var Range = yup.number().min(0).max(5).default(0) var Specify = yup.object({ times: yup.number().default(0), specify: yup.string() }); var BeforeAfter = yup.object({ before: yup.number().min(0).max(5), after: yup.number().min(0).max(5), }); var Day = yup.object({ started: yup.boolean().default(false), date: yup.date(), firstOfWeek: yup.date(), dayOfWeek: yup.number().min(0).max(7), week: yup.number().min(1).max(52), year: yup.number(), use: Range, suicide: Range, selfHarm: Range, pain: Range, sadness: Range,
const invoiceValidationSchema = ({ cmscontactsupportedchars, cmsnamelocationsupportedchars, maxlocationlength, minlocationlength, mincontactlength, maxcontactlength, minnamelength, maxnamelength, minlineitemcollength, maxlineitemcollength, invoicefieldsupportedchars }) => Yup.object().shape({ name: Yup.string() .required("required") .min(minnamelength) .max(maxnamelength) .matches(...fieldMatcher("Name", cmsnamelocationsupportedchars)), location: Yup.string() .required("required") .min(minlocationlength) .max(maxlocationlength) .matches(...fieldMatcher("Location", cmsnamelocationsupportedchars)), contact: Yup.string() .required("required") .min(mincontactlength) .max(maxcontactlength) .matches(...fieldMatcher("Contact", cmscontactsupportedchars)), rate: Yup.number() .required("required") .min(5) .max(500), address: Yup.string().required("required"), lineitems: Yup.array() .of( Yup.object().shape({ type: Yup.string() .required("required") .oneOf(["1", "2", "3"]), domain: Yup.string() .required("required") .min(minlineitemcollength) .max(maxlineitemcollength) .matches(...fieldMatcher("Domain", invoicefieldsupportedchars)), subdomain: Yup.string() .required("required") .min(minlineitemcollength) .max(maxlineitemcollength) .matches(...fieldMatcher("Sub domain", invoicefieldsupportedchars)), description: Yup.string() .min(minlineitemcollength) .max(maxlineitemcollength) .matches( ...fieldMatcher("Description", invoicefieldsupportedchars) ), labour: Yup.number(), expense: Yup.number() }) ) .min(1) });
import _ from 'lodash' import moment from 'moment' import service from 'feathers-knex' import yup from 'yup' import knex from '../database' import {populateUser, restrictToPlayerOrAdmin, restrictToAdmin, verifyToken, updateTimestamps, validate} from '../hooks' const schema = yup.object().shape({ item_id: yup.number() // eslint-disable-line camelcase .integer() .when('$method', { is: 'patch', otherwise: yup.number().required() }) .when('$method', { is: 'create', then: yup.number().test('current_auction', 'Must be bid on the current auction', function (value) { const context = this.options.context const settings = context.settings return value === settings.item_id || context.params.user.admin }) }), team_id: yup.number() // eslint-disable-line camelcase .integer() .when('$method', { is: 'patch', otherwise: yup.number().required() })