Best JavaScript code snippet using unexpected
Integration.js
Source:Integration.js
1import { deleteData, getData, postData } from "./Http"2import { fireEvent, SUCCESS, FAIL } from "../helpers/eventDispatcher"3import { API_RESPONSE_KEY, DELETED_BUNDLE, HTTP_STATUS } from "../helpers/constants";4import i18n from "../i18n";5// endpoints6const urlOrganisations = `${process.env.REACT_APP_PUBLIC_API_URL}/organisation/`7const urlCategories = `${process.env.REACT_APP_PUBLIC_API_URL}/category/`8const urlBundles = `${process.env.REACT_APP_PUBLIC_API_URL}/bundles/`9const urlBundleGroups = `${process.env.REACT_APP_PUBLIC_API_URL}/bundlegroups/`10const urlUsers = `${process.env.REACT_APP_PUBLIC_API_URL}/users/`11const urlKC = `${process.env.REACT_APP_PUBLIC_API_URL}/keycloak/`12//Bundle group version urls13const urlBundleGroupVersion = `${process.env.REACT_APP_PUBLIC_API_URL}/bundlegroupversions/`14const urlBundleGroupsVersionsFilteredPaged = `${process.env.REACT_APP_PUBLIC_API_URL}/bundlegroupversions/filtered`15// checks if the input data contain an error and sends back either the error itself or the actual data16const checkForErrorsAndSendResponse = (data, isError, objectLabel) => {17 if (isError) {18 return {19 errorBody: data,20 isError,21 }22 } else {23 return {24 [objectLabel]: data,25 isError,26 }27 }28}29const eventHandler = (isError, failMessage, successMessage) => {30 if (successMessage) {31 if (!isError) {32 fireEvent(SUCCESS, successMessage)33 }34 }35 if (isError) {36 console.error(`[ --- FATAL ERROR --- ] ${failMessage}`)37 fireEvent(FAIL, failMessage)38 }39}40/*********************41 * ORGANISATIONS *****42 *********************/43export const getAllOrganisations = async () => {44 let { data, isError } = await getData(urlOrganisations)45 eventHandler(46 isError,47 `${i18n.t('toasterMessage.impossibleToLoadOrganisations')} ${data ? data.message : ""}`48 )49 return checkForErrorsAndSendResponse(data, isError, "organisationList")50}51export const getSingleOrganisation = async (id) => {52 const { data, isError } = await getData(urlOrganisations, id)53 eventHandler(54 isError,55 `${i18n.t('toasterMessage.impossibleToLoadOrganisation')} ${data ? data.message : ""}`56 )57 return checkForErrorsAndSendResponse(data, isError, "organisation")58}59export const addNewOrganisation = async (organisationData) => {60 const { data, isError } = await postData(urlOrganisations, organisationData)61 eventHandler(62 isError,63 `${i18n.t('toasterMessage.impossibleToCreateOrganisation')} ${data ? data.message : ""}`,64 `${i18n.t('component.bundleModalFields.organisation')} ${data.data ? data.data.name : ""} ${i18n.t('toasterMessage.created')}`65 )66 return checkForErrorsAndSendResponse(data, isError, "newOrganisation")67}68export const editOrganisation = async (organisationData, id) => {69 const { data, isError } = await postData(70 urlOrganisations,71 organisationData,72 id73 )74 eventHandler(75 isError,76 `${i18n.t('toasterMessage.impossibleToUpdateOrganisation')} ${data ? data.message : ""}`,77 `${i18n.t('component.bundleModalFields.organisation')} ${data.data ? data.data.name : ""} ${i18n.t('toasterMessage.updated')}`78 )79 return checkForErrorsAndSendResponse(data, isError, "editedOrganisation")80}81export const deleteOrganisation = async (id) => {82 const { data, isError } = await deleteData(urlOrganisations, id)83 eventHandler(84 isError,85 `${i18n.t('toasterMessage.impossibleToDeleteOrganisation')} ${data ? data.message : ""}`,86 `${i18n.t('component.bundleModalFields.organisation')} ${data.data ? data.data.name : ""} ${i18n.t('toasterMessage.deleted')}`87 )88 return checkForErrorsAndSendResponse(data, isError, "deletedOrganisation")89}90/*********************91 * CATEGORIES ********92 *********************/93export const getAllCategories = async () => {94 const { data, isError } = await getData(urlCategories)95 eventHandler(96 isError,97 `${i18n.t('toasterMessage.impossibleToLoadCategory')} ${data ? data.message : ""}`98 )99 return checkForErrorsAndSendResponse(data, isError, "categoryList")100}101export const getSingleCategory = async (id) => {102 const { data, isError } = await getData(urlCategories, id)103 eventHandler(104 isError,105 `${i18n.t('toasterMessage.impossibleToLoadCategory')} ${data ? data.message : ""}`106 )107 108 return checkForErrorsAndSendResponse(data, isError, "category")109}110export const addNewCategory = async (categoryData) => {111 const { data, isError } = await postData(urlCategories, categoryData)112 eventHandler(113 isError,114 `${i18n.t('toasterMessage.impossibleToCreateCategory')} ${data ? data.message : ""}`,115 `${i18n.t('component.bundleModalFields.category')} ${data.data ? data.data.name : ""} ${i18n.t('toasterMessage.created')}`116 )117 return checkForErrorsAndSendResponse(data, isError, "newCategory")118}119export const editCategory = async (categoryData, id) => {120 const { data, isError } = await postData(urlCategories, categoryData, id)121 eventHandler(122 isError,123 `${i18n.t('toasterMessage.impossibleToUpdateCategory')} ${data ? data.message : ""}`,124 `${i18n.t('component.bundleModalFields.category')} ${data.data ? data.data.name : ""} ${i18n.t('toasterMessage.updated')}`125 )126 return checkForErrorsAndSendResponse(data, isError, "editedCategory")127}128const CATEGORY_APPLIED_ON_BUNDLE_GROUP_MSG = "This category is already in use."129export const deleteCategory = async (id, categoryName) => {130 const { data, isError } = await deleteData(urlCategories, id)131 const dataMessageLength = data.message ? data.message.split(" ").length : null132 const statusCode = dataMessageLength ? data.message.split(" ")[dataMessageLength - 1] : 0133 if (statusCode && statusCode === HTTP_STATUS.EXPECTATION_FAILED) {134 data.message = CATEGORY_APPLIED_ON_BUNDLE_GROUP_MSG135 }136 eventHandler(137 isError,138 `${i18n.t('toasterMessage.impossibleToDeleteCategory')} ${data ? data.message : ""}`,139 `${i18n.t('component.bundleModalFields.category')} ${categoryName ? categoryName : ""} ${i18n.t('toasterMessage.deleted')}`140 )141 return checkForErrorsAndSendResponse(data, isError, "deletedCategory")142}143/*********************144 * BUNDLES ***********145 *********************/146export const getAllBundles = async () => {147 const { data, isError } = await getData(urlBundles)148 eventHandler(149 isError,150 `${i18n.t('toasterMessage.impossibleToLoadBundles')} ${data ? data.message : ""}`151 )152 return checkForErrorsAndSendResponse(data, isError, "bundleList")153}154export const getAllBundlesForABundleGroup = async (id) => {155 const newUrl = `${urlBundles}?bundleGroupVersionId=${id}`156 const { data, isError } = await getData(newUrl)157 eventHandler(158 isError,159 `${i18n.t('toasterMessage.impossibleToLoadBundles')} ${data ? data.message : ""}`160 )161 return checkForErrorsAndSendResponse(data, isError, "bundleList")162}163export const getSingleBundle = async (id) => {164 const { data, isError } = await getData(urlBundles, id)165 eventHandler(166 isError,167 `${i18n.t('toasterMessage.impossibleToLoadBundle')} ${data ? data.message : ""}`168 )169 return checkForErrorsAndSendResponse(data, isError, "bundleGroup")170}171export const addNewBundle = async (bundleData) => {172 const { data, isError } = await postData(urlBundles, bundleData)173 eventHandler(174 isError,175 `${i18n.t('toasterMessage.impossibleToCreateBundle')} ${data ? data.message : ""}`,176 `${i18n.t('toasterMessage.bundle')} ${data.data ? data.data.name : ""} ${i18n.t('toasterMessage.created')}`177 )178 return checkForErrorsAndSendResponse(data, isError, "newBundle")179}180export const editBundle = async (bundleData, id) => {181 const { data, isError } = await postData(urlBundles, bundleData, id)182 eventHandler(183 isError,184 `${i18n.t('toasterMessage.impossibleToUpdateBundle')} ${data ? data.message : ""}`,185 `${i18n.t('toasterMessage.bundle')} ${data.data ? data.data.name : ""} ${i18n.t('toasterMessage.updated')}`186 )187 return checkForErrorsAndSendResponse(data, isError, "editedBundle")188}189/*********************190 * BUNDLE GROUPS *****191 *********************/192export const getAllBundleGroups = async (organisationId) => {193 let url = urlBundleGroups194 if (organisationId)195 url = urlBundleGroups + "?organisationId=" + organisationId196 const { data, isError } = await getData(url)197 eventHandler(198 isError,199 `${i18n.t('toasterMessage.impossibleToLoadBundleGroups')} ${data ? data.message : ""}`200 )201 return checkForErrorsAndSendResponse(data, isError, "bundleGroupList")202}203/**204 * GET bundle groups/versions filtered205 * @param {*} page 206 * @param {*} pageSize 207 * @param {*} organisationId 208 * @param {*} categoryIds 209 * @param {*} statuses 210 * @returns 211 */212export const getAllBundleGroupsFilteredPaged = async (213 page,214 pageSize,215 organisationId,216 categoryIds,217 statuses,218 searchText = null219) => {220 let url = `${urlBundleGroupsVersionsFilteredPaged}?page=${page}&pageSize=${pageSize}`221 if (categoryIds && categoryIds.length > 0) {222 url =223 url +224 "&" +225 categoryIds.map((categoryId) => `categoryIds=${categoryId}`).join("&")226 }227 if (statuses && statuses.length > 0) {228 statuses.map((status) => `statuses=${status}`).join("&")229 url = url + "&" + statuses.map((status) => `statuses=${status}`).join("&")230 }231 if (organisationId) url = url + "&organisationId=" + organisationId232 if (searchText) url = url + `&searchText=${searchText}`233 const { data, isError } = await getData(url)234 eventHandler(235 isError,236 `Impossible to load bundle groups: ${data ? data.message : ""}`237 )238 return checkForErrorsAndSendResponse(data, isError, "bundleGroupList")239}240export const getSingleBundleGroup = async (id) => {241 const { data, isError } = await getData(urlBundleGroups, id)242 eventHandler(243 isError,244 `Impossible to load bundle group: ${data ? data.message : ""}`245 )246 return checkForErrorsAndSendResponse(data, isError, "bundleGroup")247}248export const addNewBundleGroup = async (bundleGroupData) => {249 const { data, isError } = await postData(urlBundleGroups, bundleGroupData)250 eventHandler(251 isError,252 `${i18n.t('toasterMessage.impossibleToCreateBundleGroup')} ${data ? data.message : ""}`,253 `${i18n.t('toasterMessage.bundleGroup')} ${data.data ? data.data.name : ""} ${i18n.t('toasterMessage.created')}`254 )255 return checkForErrorsAndSendResponse(data, isError, "newBundleGroup")256}257export const editBundleGroup = async (bundleGroupData, id) => {258 const { data, isError } = await postData(urlBundleGroups, bundleGroupData, id)259 eventHandler(260 isError,261 `${i18n.t('toasterMessage.impossibleToUpdateBundleGroup')} ${data ? data.message : ""}`,262 `${i18n.t('toasterMessage.bundleGroup')} ${data.data ? data.data.name : ""} ${i18n.t('toasterMessage.updated')}`263 )264 return checkForErrorsAndSendResponse(data, isError, API_RESPONSE_KEY.EDITED_BUNDLE_GROUP)265}266export const deleteBundle = async (id, bundleName) => {267 const { data, isError } = await deleteData(urlBundleGroups, id)268 eventHandler(269 isError,270 `${i18n.t('toasterMessage.impossibleToDeleteBundle')} ${data ? data.message : ""}`,271 `${i18n.t('toasterMessage.bundle')} ${bundleName ? bundleName : ""} ${i18n.t('toasterMessage.deleted')}`272 )273 return checkForErrorsAndSendResponse(data, isError, DELETED_BUNDLE)274}275/*********************276 * USERS *************277 *********************/278// POST input: username and organization id -> create a user and assign it to that organization279// path: organization id280// req body: username281export const createAUserForAnOrganisation = async (282 organisationId,283 userData,284 type285) => {286 const newUrl = `${urlUsers}${organisationId}`287 const userDataObject = {288 username: userData,289 }290 const { data, isError } = await postData(newUrl, userDataObject)291 if (type === 'update') {292 debugger293 eventHandler(isError,294 `${i18n.t('toasterMessage.impossibleToCreateUser')}`,295 `${i18n.t('toasterMessage.user')} ${userData ? userData : ""} ${i18n.t('toasterMessage.updated')}`296 )297 } else {298 eventHandler(isError,299 `${i18n.t('toasterMessage.impossibleToCreateUser')}`,300 `${i18n.t('toasterMessage.user')} ${userData ? userData : ""} ${i18n.t('toasterMessage.created')}`301 )302 }303 return checkForErrorsAndSendResponse(data, isError, "newUserForOrganization")304}305// GET input: nothing -> get all the users306export const getAllUsers = async () => {307 const { data, isError } = await getData(urlUsers)308 eventHandler(isError, `${i18n.t('toasterMessage.impossibleToLoadUsers')}`) 309 return checkForErrorsAndSendResponse(data, isError, "userList")310}311// GET input: organization id -> get all the users for that organization312// query string: organization id313export const getAllUserForAnOrganisation = async (organisationId) => {314 const newUrl = `${urlUsers}?organisationId=${organisationId}`315 const { data, isError } = await getData(newUrl)316 eventHandler(isError, `${i18n.t('toasterMessage.impossibleToLoadUsers')}`)317 return checkForErrorsAndSendResponse(data, isError, "userList")318}319// DELETE input: username -> delete the user320// path: username321export const deleteUser = async (username) => {322 const newUrl = `${urlUsers}${username}`323 const { data, isError } = await deleteData(newUrl)324 eventHandler(isError, `${i18n.t('toasterMessage.impossibleToDeleteUser')}`, `User deleted`)325 return data326}327// DELETE input: organization id and username -> remove the user from that organization328// path: username329// path: organization id330export const removeUserFromOrganisation = async (organisationId, username, type) => {331 const newUrl = `${urlUsers}${organisationId}/user/${username}`332 const { data, isError } = await deleteData(newUrl)333 // while updating user no need to show 'user removed toaster'334 if (type === 'update') {335 eventHandler(isError, `${i18n.t('toasterMessage.impossibleToRemoveUser')}`, ``);336 } else {337 eventHandler(isError, `${i18n.t('toasterMessage.impossibleToRemoveUser')}`, `${i18n.t('toasterMessage.userRemovedFromTheOrganisation')}`);338 }339 return data340}341/**342 * Get a portal user by username.343 * @param {*} username 344 * @returns 345 */346 export const getPortalUserByUsername = async (username) => {347 const { data, isError } = await getData(urlUsers + username)348 return checkForErrorsAndSendResponse(data, isError, API_RESPONSE_KEY.PORTAL_USER);349}350/*********************351 * KC *************352 *********************/353/*354 {355 "id": "e7a0ae5d-59ab-40c7-a510-ae4756cc5044",356 "created": "2021-09-02T21:49:36.409+00:00",357 "username": "admin",358 "enabled": true,359 "firstName": null,360 "lastName": null,361 "email": null,362 "organisationIds": []363 }364}365*/366export const getAllKCUsers = async () => {367 const newUrl = `${urlKC}users`368 const { data, isError } = await getData(newUrl)369 return checkForErrorsAndSendResponse(data, isError, "kcUsers")370}371/**************************372 * Bundle Group Version373***************************/374/**375 * Add new bundle group version376 * @param {*} bundleGroupVersionData 377 * @param {*} bundleGroupId 378 * @returns 379 */380 export const addNewBundleGroupVersion = async (bundleGroupVersionData) => {381 const { data, isError } = await postData(urlBundleGroupVersion, bundleGroupVersionData)382 eventHandler(383 isError,384 `${i18n.t('toasterMessage.unableToAddBundleGroupVersion')} ${data ? data.message : ""}`,385 `${i18n.t('toasterMessage.bundleGroupVersion')} ${data.data ? data.data.name : ""} saved`386 )387 return checkForErrorsAndSendResponse(data, isError, API_RESPONSE_KEY.EDITED_BUNDLE_GROUP)388}389/**390 * Get all bundle group versions by bundleGroupId391 * @param {*} bundleGroupId 392 */393 export const getAllBundleGroupVersionByBundleGroupId = async (bundleGroupId, page, pageSize, bundleStatuses) => {394 // let url = `${urlBundleGroupVersion}versions/${bundleGroupId}?page=${page}&pageSize=${pageSize}`;395 let url = `${urlBundleGroupVersion}versions/${bundleGroupId}?page=${page}&pageSize=${pageSize}${(!bundleStatuses || bundleStatuses.toString() === '-1') ? '' : `&statuses=${bundleStatuses}`}`;396 const { data, isError } = await getData(url);397 eventHandler(398 isError,399 `${i18n.t('toasterMessage.impossibleToLoadBundleGroupVersions')} : ${data ? data.message : ""}`400 )401 return checkForErrorsAndSendResponse(data, isError, "versions")402}403/**404 * Delete a bundle group version405 * @param {*} id 406 * @param {*} bundleName 407 * @returns 408 */409export const deleteBundleGroupVersion = async (bundleGroupVersionId) => {410 const { data, isError } = await deleteData(urlBundleGroupVersion, bundleGroupVersionId);411 eventHandler(412 isError,413 `${i18n.t('toasterMessage.impossibleToDeleteBundle')} ${data ? data.message : ""}`,414 `${i18n.t('toasterMessage.bundleGroupVersion')} ${i18n.t('toasterMessage.deleted')}`415 )416 return checkForErrorsAndSendResponse(data, isError, DELETED_BUNDLE);417}418/**419 * Update a bundle group version420 * @param {*} bundleGroupVersionData 421 * @param {*} bundleGroupVersionId 422 * @returns 423 */424export const editBundleGroupVersion = async (bundleGroupVersionData, bundleGroupVersionId) => {425 const { data, isError } = await postData(urlBundleGroupVersion, bundleGroupVersionData, bundleGroupVersionId)426 eventHandler(427 isError,428 `${i18n.t('toasterMessage.impossibleToUpdateBundleGroup')} ${data ? data.message : ""}`,429 `${i18n.t('toasterMessage.bundleGroup')} ${bundleGroupVersionData.name} ${i18n.t('toasterMessage.updated')}`430 )431 return checkForErrorsAndSendResponse(data, isError, API_RESPONSE_KEY.EDITED_BUNDLE_GROUP)432}433/**434 * Get bundle group details by bundle group version id435 * @param {*} bundleGroupVersionId 436 * @returns 437 */438 export const getBundleGroupDetailsByBundleGroupVersionId = async (bundleGroupVersionId) => {439 let newUrl = `${urlBundleGroupVersion}${bundleGroupVersionId}`;440 const { data, isError } = await getData(newUrl)441 eventHandler(isError, `${i18n.t('toasterMessage.impossibleToLoadUsers')}`)442 return checkForErrorsAndSendResponse(data, isError, "bgVersionDetails")...
formValidator.js
Source:formValidator.js
1import {monthFullNames} from 'lib/formHelpers/defaultData.js';2// Validate add new experience form (Work/Education/Accomplishment)3const experienceValidator = values => {4 if (values.start_year) {5 values.start_year = values.start_year.toString();6 }7 if (values.end_year) {8 values.end_year = values.end_year.toString();9 }10 const {11 type,12 start_month,13 end_month,14 start_year,15 end_year,16 is_current,17 location,18 host,19 title,20 degree,21 degree_other,22 link,23 link_name,24 description,25 achievements,26 } = values;27 let isError = false;28 let err = {};29 if (type !== 'Accomplishment' && !host) {30 isError = true;31 err.host_error = 'Required';32 }33 if (type === 'Education' && !degree) {34 isError = true;35 err.degree_error = 'Required';36 }37 if (type === 'Education' && degree) {38 if (degree === 'Other' && !degree_other) {39 isError = true;40 err.degreeOther_error = 'Required';41 }42 if (degree_other && degree_other.length > 100) {43 isError = true;44 err.degreeOther_error =45 'Type of Education must be less than 100 characters';46 }47 }48 if (!title) {49 isError = true;50 err.title_error = 'Required';51 }52 if (link && !link.startsWith('https://')) {53 isError = true;54 err.link_error = 'Link must start with "https://"';55 }56 if (link && link.length > 255) {57 isError = true;58 err.link_error = 'Link must be less than 255 characters';59 }60 if ((link && !link_name) || (link && link_name && link_name.length < 1)) {61 isError = true;62 err.linkName_error = 'Link name is required when you enter URL';63 }64 // check if start_month is null, invalid month name, or 'none'65 if (66 type !== 'Accomplishment' &&67 (!start_month || !monthFullNames.includes(start_month))68 ) {69 isError = true;70 err.startMonth_error = 'Required';71 }72 // check if start_year is null or '0'73 if (type !== 'Accomplishment' && (!start_year || start_year === '0')) {74 isError = true;75 err.startYear_error = 'Required';76 }77 if (type !== 'Accomplishment' && !location) {78 isError = true;79 err.location_error = 'Required';80 }81 // require end_month and end_year if is_current is false82 if (type !== 'Accomplishment' && is_current === false) {83 if (!end_month || !monthFullNames.includes(end_month)) {84 isError = true;85 err.endMonth_error = 'Required';86 }87 if (!end_year || end_year === '0') {88 isError = true;89 err.endYear_error = 'Required';90 }91 }92 if (description && description.length > 750) {93 isError = true;94 err.description_error = 'Your content is too long. Maximum 750 characters.';95 }96 if (achievements && achievements.length > 0) {97 achievements.forEach(achievement => {98 if (achievement.description.length > 750) {99 isError = true;100 err.achievements_error =101 'Your content is too long. Maximum 750 characters.';102 }103 });104 }105 if (106 !is_current &&107 start_month &&108 start_year &&109 end_month &&110 end_year &&111 end_month !== 'none' &&112 end_year !== '0'113 ) {114 // if same year (start-end), check if months are in the correct order115 if (116 start_year === end_year &&117 monthFullNames.indexOf(end_month) < monthFullNames.indexOf(start_month)118 ) {119 isError = true;120 err.endMonth_error = 'End month must be later than start month';121 }122 // end year cannot be less than start year123 if (end_year < start_year) {124 isError = true;125 err.endYear_error = 'End year must be greater than start year';126 }127 }128 return {isError, err};129};130const newProfileValidator = values => {131 const {first_name, last_name, email, phone_primary, terms_agreement} = values;132 let isError = false;133 let err = {};134 if (!first_name) {135 isError = true;136 err.firstName_error = 'Required';137 }138 if (!last_name) {139 isError = true;140 err.lastName_error = 'Required';141 }142 if (!email) {143 isError = true;144 err.email_error = 'Required';145 } else if (!validateEmail(email)) {146 isError = true;147 err.email_error = 'Invalid email address';148 }149 if (!phone_primary || phone_primary.replace(/\D/g, '').length < 6) {150 isError = true;151 err.phonePrimary_error = 'Required';152 }153 if (!terms_agreement) {154 isError = true;155 err.termsAgreement_error = 'Required';156 }157 return {isError, err};158};159// Validate RegEx160const validateEmail = input => {161 const mailFormat = /^[A-Z0-9_%!+-][A-Z0-9._%!+-]*@[A-Z0-9][A-Z0-9-.]+[^.]\.[A-Z]{2,}$/i;162 if (input.match(mailFormat) && input.split('@')[0].length < 64) {163 return true;164 } else {165 return false;166 }167};168const opportunityValidator = values => {169 const {org_name, title, short_description, gdoc_link} = values;170 let isError = false;171 let err = {};172 if (!org_name || org_name.length === 0) {173 isError = true;174 err.orgName_error = 'Required';175 } else if (org_name && org_name.length > 200) {176 isError = true;177 err.orgName_error = 'Organization name must be less than 200 characters';178 }179 if (!title || title.length === 0) {180 isError = true;181 err.title_error = 'Required';182 } else if (title && title.length > 200) {183 isError = true;184 err.title_error = 'Job title must be less than 200 characters';185 }186 if (!short_description || short_description.length === 0) {187 isError = true;188 err.shortDescription_error = 'Required';189 } else if (short_description && short_description.length > 2000) {190 isError = true;191 err.shortDescription_error =192 'Short description must be less than 2,000 characters';193 }194 if (!gdoc_link || gdoc_link.length === 0) {195 isError = true;196 err.link_error = 'Required';197 } else if (198 gdoc_link &&199 !gdoc_link.startsWith('https://docs.google.com/document/d/')200 ) {201 isError = true;202 err.link_error =203 'Link must start with "https://docs.google.com/document/d/"';204 }205 if (gdoc_link && gdoc_link.length > 200) {206 isError = true;207 err.link_error = 'Link must be less than 200 characters';208 }209 return {isError, err};210};211const interestValidator = interestText => {212 let isError = false;213 let err = {};214 if (!interestText) {215 isError = true;216 err.interestText_error = 'Required';217 } else if (interestText && interestText.length > 2000) {218 isError = true;219 err.interestText_error =220 'Interest statement must be less than 2,000 characters';221 }222 return {isError, err};223};224const interviewScheduledValidator = values => {225 const {interview_date, interview_time} = values;226 let isError = false;227 let err = {};228 if (!interview_date || interview_date.length === 0) {229 isError = true;230 err.interviewDate_error = 'Required';231 } else if (interview_date.toString() === 'Invalid Date') {232 isError = true;233 }234 if (!interview_time || interview_time.length === 0) {235 isError = true;236 err.interviewTime_error = 'Required';237 } else if (interview_time.toString() === 'Invalid Date') {238 isError = true;239 }240 return {isError, err};241};242const contactInfoValidator = values => {243 const {first_name, last_name, email, phone_primary} = values;244 const {245 gender,246 gender_other,247 pronoun,248 pronoun_other,249 hear_about_us,250 hear_about_us_other,251 race,252 } = values.profile;253 const {254 street1,255 city,256 state,257 zip_code,258 country,259 } = values.profile.address_primary;260 let isError = false;261 let err = {};262 function isNumeric(value) {263 return /^-{0,1}\d+$/.test(value);264 }265 if (!first_name) {266 isError = true;267 err.firstName_error = 'Required';268 }269 if (!last_name) {270 isError = true;271 err.lastName_error = 'Required';272 }273 if (!email) {274 isError = true;275 err.email_error = 'Required';276 } else if (email && !validateEmail(email)) {277 isError = true;278 err.email_error = 'Invalid email address';279 }280 if (!phone_primary || phone_primary.replace(/\D/g, '').length < 6) {281 isError = true;282 err.phonePrimary_error = 'Required';283 }284 if (!street1 || street1.length === 0) {285 isError = true;286 err.street1_error = 'Required';287 }288 if (!city || city.length === 0) {289 isError = true;290 err.city_error = 'Required';291 }292 if (!state || state.length === 0) {293 isError = true;294 err.state_error = 'Required';295 }296 if (!zip_code || zip_code.length === 0) {297 isError = true;298 err.zipCode_error = 'Required';299 } else if (!isNumeric(zip_code)) {300 isError = true;301 err.zipCode_error = 'Invalid value. Please enter numbers only';302 } else if (zip_code.length !== 5) {303 isError = true;304 err.zipCode_error = 'Invalid value. Please enter five-digit numbers only';305 }306 if (!country || country.length === 0) {307 isError = true;308 err.country_error = 'Required';309 }310 if (race.not_listed && (!race.race_other || race.race_other.length === 0)) {311 isError = true;312 err.raceOther_error = 'Required';313 }314 if (315 hear_about_us &&316 hear_about_us === 'Other' &&317 (!hear_about_us_other || hear_about_us_other.length === 0)318 ) {319 isError = true;320 err.hearAboutUsOther_error = 'Required';321 }322 if (323 gender &&324 gender === 'Not Listed' &&325 (!gender_other || gender_other.length === 0)326 ) {327 isError = true;328 err.genderOther_error = 'Required';329 }330 if (331 pronoun &&332 pronoun === 'Not Listed' &&333 (!pronoun_other || pronoun_other.length === 0)334 ) {335 isError = true;336 err.pronounOther_error = 'Required';337 }338 return {isError, err};339};340const interestsAndGoalsValidator = values => {341 const {342 job_search_status,343 current_job_status,344 current_edu_status,345 years_exp,346 previous_bcorps_program,347 programs_completed,348 } = values.profile;349 const allValues = Object.values(programs_completed);350 let isError = false;351 let err = {};352 if (!job_search_status || job_search_status.length === 0) {353 isError = true;354 err.jobSearchStatus_error = 'Required';355 }356 if (!current_job_status || current_job_status.length === 0) {357 isError = true;358 err.currentJobStatus_error = 'Required';359 }360 if (!current_edu_status || current_edu_status.length === 0) {361 isError = true;362 err.currentEduStatus_error = 'Required';363 }364 if (!years_exp || years_exp.length === 0) {365 isError = true;366 err.yearsExp_error = 'Required';367 }368 if (369 previous_bcorps_program &&370 previous_bcorps_program === 'Yes' &&371 !allValues.includes(true)372 ) {373 isError = true;374 err.programsCompleted_error = 'Required';375 }376 return {isError, err};377};378const programsAndEligibilityValidator = values => {379 const {program_apps} = values;380 const allValues = Object.values(program_apps).map(381 program => program.is_interested382 );383 allValues.push(values.profile.needs_help_programs);384 let isError = false;385 let err = {};386 if (!allValues.includes(true)) {387 isError = true;388 err.interestedPrograms_error = 'Required';389 }390 return {isError, err};391};392const valueAlignmentValidator = values => {393 const {value_question1, value_question2} = values.profile;394 let isError = false;395 let err = {};396 if (!value_question1 || value_question1.length === 0) {397 isError = true;398 err.valueQuestion1_error = 'Required';399 }400 if (value_question1 && value_question1.length > 1500) {401 isError = true;402 err.valueQuestion1_error =403 'You have reached the maximum limit of 1,500 characters';404 }405 if (!value_question2 || value_question2.length === 0) {406 isError = true;407 err.valueQuestion2_error = 'Required';408 }409 if (value_question2 && value_question2.length > 2500) {410 isError = true;411 err.valueQuestion2_error =412 'You have reached the maximum limit of 2,500 characters';413 }414 return {isError, err};415};416export {417 newProfileValidator,418 experienceValidator,419 opportunityValidator,420 interestValidator,421 interviewScheduledValidator,422 contactInfoValidator,423 interestsAndGoalsValidator,424 programsAndEligibilityValidator,425 valueAlignmentValidator,...
register.js
Source:register.js
1import React, { Component } from 'react';2import { Link } from 'react-router-dom';3import Axios from 'axios';4import home from '../images/logo3rm.png';5const regExp = RegExp(6 /^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]+$/7)8const formValid = ({ isError, ...rest }) => {9 let isValid = false;10 Object.values(isError).forEach(val => {11 if (val.length > 0) {12 isValid = false13 } else {14 isValid = true15 }16 });17 Object.values(rest).forEach(val => {18 if (val === null) {19 isValid = false20 } else {21 isValid = true22 }23 });24 return isValid;25};26class RegisterComponent extends React.Component {27 constructor(props) {28 super(props);29 this.state = {30 fname: '',31 lname: '',32 email: '',33 loginid: '',34 password: '',35 contact: '',36 msgResponse:'',37 logoURL:home,38 isError: {39 fname: '',40 lname: '',41 email: '',42 loginid: '',43 password: '',44 contact: ''45 }46 }47 }48 49 formValChange = e => {50 e.preventDefault();51 const { name, value } = e.target;52 let isError = {... this.state.isError} ;53 switch (name) {54 case "fname":55 isError.fname =56 value.length < 4 ? "Atleast 4 characaters required" : "";57 // this.setState({fname:e.target.value})58 59 break;60 case "lname":61 isError.lname =62 value.length < 4 ? "Atleast 4 characaters required" : "";63 break;64 case "email":65 isError.email = regExp.test(value)66 ? ""67 : "Email address is invalid";68 break;69 case "loginid":70 isError.loginid =71 value.length < 5 ? "Atleast 5 characaters required" : "";72 break;73 case "password":74 isError.password =75 value.length < 6 ? "Atleast 6 characaters required" : "";76 break;77 case "contact":78 isError.contact =79 value.length < 10 ? "Atleast 10 characaters required" : "";80 break;81 default:82 break;83 }84 this.setState({85 isError,86 [name]: value87 88 })89 90 };91 onSubmit = e => {92 e.preventDefault();93 if (formValid(this.state)) {94 console.log(this.state)95 96 } else {97 console.log("Form is invalid!");98 }99 this.saveUser()100 };101 saveUser=()=>{102 let requestbody={103 "firstname":this.state.fname,104 "lastname":this.state.lname,105 "email":this.state.email,106 "loginid":this.state.loginid,107 "password":this.state.password,108 "contact":this.state.contact109 }110 111 112 Axios.post('http://localhost:9511/api/v1/user/register', requestbody)113 .then(response => {114 console.log(response);115 this.props.history.push('/login')116 }, error => {117 console.log(error)118 this.setState({ msgResponse: "enter valid credentials.." })119 })120 }121 render() {122 const isError = {... this.state.isError} ;123 124 return (125 <div>126 <div className="data">127 <img src={this.state.logoURL} style={{width:200,marginTop:30,alignSelf:'center'}} />128 <h2 style={{marginLeft:126,marginTop:-45,color:"whitesmoke"}}><i><b>Tweet</b></i></h2>129 <h3 style={{marginLeft:50,color:"whitesmoke"}}>Post <b>Here!!</b> Share your <b>Thoughts!!</b></h3>130 </div>131 <div id="box">132 <h3 align="center">Register Here!!!</h3><br></br>133 <form onSubmit={this.onSubmit} noValidate>134 <div class="form-group row">135 <label class="col-sm-4">Firstname</label>136 <div class="col-sm-8">137 <input type="text" 138 className={isError.fname.length > 0 ? "is-invalid form-control" : "form-control"} 139 name="fname" placeholder="Firstname" onChange={this.formValChange}/>140 {isError.fname.length > 0 && (141 <span className="invalid-feedback">{isError.fname}</span>)}142 </div>143 </div>144 <div class="form-group row">145 <label class="col-sm-4">Lastname</label>146 <div class="col-sm-8">147 <input type="text"148 className={isError.lname.length >0 ? "is-invalid form-control" : "form-control"} 149 name="lname" placeholder="Lastname" onChange={this.formValChange} />150 {isError.lname.length > 0}<span className="invalid-feedback">{isError.lname}</span>151 </div>152 </div>153 <div class="form-group row">154 <label class="col-sm-4">Email</label>155 <div class="col-sm-8">156 <input type="email"157 className={isError.email.length > 0 ? "is-invalid form-control" : "form-control"}158 name="email" placeholder="Email"159 onChange={this.formValChange} />160 {isError.email.length > 0}161 <span className="invalid-feedback">{isError.email}</span>162 163 </div>164 </div>165 <div class="form-group row">166 <label class="col-sm-4">LoginID</label>167 <div class="col-sm-8">168 <input type="text" 169 className={isError.loginid.length > 0 ? "is-invalid form-control" : "form-control"}170 name="loginid" placeholder="LoginID" onChange={this.formValChange} />171 {isError.loginid.length>0} <span className="invalid-feedack">{isError.loginid}</span> 172 </div>173 </div>174 <div class="form-group row">175 <label class="col-sm-4">Password</label>176 <div class="col-sm-8">177 <input type="password" 178 className={isError.password.length>0 ? "is-invalid form-control": "form-control"} 179 name="password" placeholder="Password" onChange={this.formValChange}/>180 {isError.password.length > 0 && (181 <span className="invalid-feedback">{isError.password}</span>)}182 </div>183 </div>184 <div class="form-group row">185 <label class="col-sm-4" >ContactNumber</label>186 <div class="col-sm-8">187 <input type="number" 188 className={isError.contact.length>0 ? "is-invalid form-control":"form-control"}189 name="contact" placeholder="Contactnumber" onChange={this.formValChange} />190 {isError.contact.length>0}<span className="invalid-feedback">{isError.contact}</span>191 </div>192 </div>193 <button type="submit" className="btn btn-primary btn-lg btn-block">Register</button>194 <span style={{ color: "red", marginLeft: "20px" }}>{this.state.msgResponse}</span>195 <p className="forgot-password text-right">196 <Link to='/login' id="reg">Already a member,login here..</Link>197 </p>198 </form>199 </div>200 </div> 201 );202 }203}...
SignUp.js
Source:SignUp.js
1import React, { Component } from 'react';2// router-dom3import { Link } from 'react-router-dom';4// css5import './SignUp.css';6// ì í¨ì± ì ê·ì7const regId = /^[a-z0-9]{4,12}$/;8const regNick = /^[ê°-í£A-Za-z0-9]{4,12}$/;9const regMail = RegExp(/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]+$/);10// ì í¨ì± ê²ì¬11// ìë¬ê° ìì¼ë©´ ë°ì12const formValid = (isError) => {13 let isValid = true;14 Object.values(isError).forEach((val) => val.length > 0 && (isValid = false));15 return isValid;16};17// ë¹ì¹¸ì´ ìì¼ë©´ ë°ì18const blankValid = ({ isError, ...rest }) => {19 let isValid = true;20 Object.values(rest).forEach((val) => val === '' && (isValid = false));21 return isValid;22};23class SignUp extends Component {24 constructor() {25 super();26 this.state = {27 nickname: '',28 email: '',29 id: '',30 password: '',31 password2: '',32 // formValid: false,33 // errorCount: null,34 isError: {35 nickname: '',36 email: '',37 id: '',38 password: '',39 password2: '',40 },41 };42 }43 onSubmit = (e) => {44 e.preventDefault();45 // if (validateForm(this.state.isError)) {46 // console.log(this.state);47 // } else {48 // console.log('sorry');49 // }50 // this.setState({ formValid: validateForm(this.state.isError) });51 // this.setState({ errorCount: countErrors(this.state.isError) });52 if (formValid(this.state.isError) && blankValid(this.state)) {53 console.log(this.state);54 } else {55 console.log('Form is invalid!');56 }57 // if (blankValid(this.state)) {58 // console.log(this.state);59 // } else {60 // console.log('Sorry!');61 // }62 };63 formValChange = (e) => {64 e.preventDefault();65 const { name, value } = e.target;66 let isError = { ...this.state.isError };67 switch (name) {68 case 'nickname':69 isError.nickname = regNick.test(value)70 ? ''71 : 'ëë¤ìì 4~12ìì íê¸, ì문, ì«ì ì¡°í©ì
ëë¤.';72 break;73 case 'email':74 isError.email = regMail.test(value)75 ? ''76 : 'ì´ë©ì¼ íìì´ ì¬ë°ë¥´ì§ ììµëë¤.';77 break;78 case 'id':79 // isError.id = value.length < 4 ? 'ìì´ëë 4ì ì´ì ì
ë ¥í´ì£¼ì¸ì.' : '';80 isError.id = regId.test(value)81 ? ''82 : 'ìì´ëë 4~12ìì ì문과 ì«ìë¡ë§ ì
ë ¥ ê°ë¥í©ëë¤.';83 break;84 case 'password':85 isError.password =86 value.length < 6 ? 'ë¹ë°ë²í¸ë 6ì ì´ìì´ì´ì¼ í©ëë¤.' : '';87 if (value.length >= 6) {88 this.setState({ password: value });89 // console.log(this.state.password);90 }91 isError.password2 =92 value !== this.state.password2 ? 'ë¹ë°ë²í¸ê° ì¼ì¹íì§ ììµëë¤.' : '';93 break;94 case 'password2':95 isError.password2 =96 value !== this.state.password ? 'ë¹ë°ë²í¸ê° ì¼ì¹íì§ ììµëë¤.' : '';97 // if (value === this.state.password) {98 this.setState({ password2: value });99 // }100 break;101 default:102 break;103 }104 this.setState({105 isError,106 [name]: value,107 });108 };109 render() {110 const { isError } = this.state;111 return (112 <div className="regibox">113 <div className="d-flex justify-content-center">114 <h3>íìê°ì
íë©´ì
ëë¤.</h3>115 </div>116 <form onSubmit={this.onSubmit} noValidate>117 <div className="form-group">118 <label>ìì´ë</label>119 <input120 type="text"121 className={122 isError.id.length > 0123 ? 'is-invalid form-control'124 : 'form-control'125 }126 name="id"127 onChange={this.formValChange}128 />129 {isError.id.length > 0 && (130 <span className="invalid-feedback">{isError.id}</span>131 )}132 </div>133 <div className="form-group">134 <label>ë¹ë°ë²í¸</label>135 <input136 type="password"137 className={138 isError.password.length > 0139 ? 'is-invalid form-control'140 : 'form-control'141 }142 name="password"143 onChange={this.formValChange}144 />145 {isError.password.length > 0 && (146 <span className="invalid-feedback">{isError.password}</span>147 )}148 </div>149 <div className="form-group">150 <label>ë¹ë°ë²í¸ íì¸</label>151 <input152 type="password"153 className={154 isError.password2.length > 0155 ? 'is-invalid form-control'156 : 'form-control'157 }158 name="password2"159 onChange={this.formValChange}160 />161 {isError.password2.length > 0 && (162 <span className="invalid-feedback">{isError.password2}</span>163 )}164 </div>165 <div className="form-group">166 <label>ëë¤ì</label>167 <input168 type="text"169 className={170 isError.nickname.length > 0171 ? 'is-invalid form-control'172 : 'form-control'173 }174 name="nickname"175 onChange={this.formValChange}176 />177 {isError.nickname.length > 0 && (178 <span className="invalid-feedback">{isError.nickname}</span>179 )}180 </div>181 <div className="form-group">182 <label>ì´ë©ì¼</label>183 <input184 type="email"185 className={186 isError.email.length > 0187 ? 'is-invalid form-control'188 : 'form-control'189 }190 name="email"191 onChange={this.formValChange}192 />193 {isError.email.length > 0 && (194 <span className="invalid-feedback">{isError.email}</span>195 )}196 </div>197 <button type="submit" className="create-btn">198 ìì± ìë£199 </button>200 <Link201 to="/"202 style={{ textDecoration: 'none', color: 'white', width: '100%' }}203 >204 <button type="submit" className="regiback-btn">205 ë¤ë¡206 </button>207 </Link>208 </form>209 </div>210 );211 }212}...
index.js
Source:index.js
1import React, { useState } from 'react';2import { StyleSheet, View } from 'react-native';3import {4 HelperText,5 Text,6 TextInput,7 Snackbar,8 ActivityIndicator,9} from 'react-native-paper';10import { useDispatch, useSelector } from 'react-redux';11import { color, fontConfig } from '../../assets';12import { BaseButton, BaseTextInput } from '../../components';13import { clearErrorAuth, registerAsync } from '../../redux/authReducer/actions';14const SignUpScreen = ({ navigation }) => {15 const dispatch = useDispatch();16 const authReducer = useSelector(state => state.authReducer);17 const [state, setState] = useState({18 name: '',19 username: '',20 email: '',21 password: '',22 showPassword: false,23 iconPassword: 'eye',24 errors: {25 name: {26 message: 'Name cannot be empty',27 isError: false,28 },29 username: {30 message: 'Username cannot be empty',31 isError: false,32 },33 email: {34 message: 'Invalid email, Here is a hint: bernard@gmail.com',35 isError: false,36 },37 password: {38 message: 'Password cannot be empty',39 isError: false,40 },41 },42 });43 const _handleTogglePassword = () => {44 setState({45 ...state,46 showPassword: !state.showPassword,47 iconPassword: state.showPassword ? 'eye' : 'eye-off',48 });49 };50 const onChangeText = (target, e) => {51 setState({ ...state, [target]: e });52 };53 const _handleSubmitRegister = () => {54 const copyState = { ...state };55 copyState.errors.name.isError = false;56 copyState.errors.username.isError = false;57 copyState.errors.email.isError = false;58 copyState.errors.password.isError = false;59 if (state.name === '') {60 copyState.errors.name.isError = true;61 }62 if (state.username === '') {63 copyState.errors.username.isError = true;64 }65 if (!state.email.includes('@')) {66 copyState.errors.email.isError = true;67 }68 if (state.password === '') {69 copyState.errors.password.isError = true;70 }71 setState(copyState);72 if (73 !state.errors.name.isError &&74 !state.errors.username.isError &&75 !state.errors.email.isError &&76 !state.errors.password.isError77 ) {78 dispatch(79 registerAsync(state.name, state.username, state.email, state.password),80 );81 }82 };83 return (84 <View style={styles.container}>85 <View style={styles.signUpTitleWrapper}>86 <Text style={styles.signUpTitleHeadingText}>87 GLiVE Account Registration88 </Text>89 <Text style={styles.signUpTitleSubHeadingText}>90 Please fill in the field below :)91 </Text>92 </View>93 <View style={styles.signUpFormWrapper}>94 <View style={styles.signUpFormControl}>95 <BaseTextInput96 mode="outlined"97 label="Name"98 onChangeText={e => onChangeText('name', e)}99 isError={state.errors.name.isError}>100 <HelperText101 type="error"102 theme={{ colors: { error: color.yellow } }}103 visible={state.errors.name.isError}>104 {state.errors.name.message}105 </HelperText>106 </BaseTextInput>107 </View>108 <View style={styles.signUpFormControl}>109 <BaseTextInput110 mode="outlined"111 label="Username"112 onChangeText={e => onChangeText('username', e)}113 value={state.username}114 isError={state.errors.username.isError}>115 <HelperText116 type="error"117 theme={{ colors: { error: color.yellow } }}118 visible={state.errors.username.isError}>119 {state.errors.username.message}120 </HelperText>121 </BaseTextInput>122 </View>123 <View style={styles.signUpFormControl}>124 <BaseTextInput125 mode="outlined"126 label="Email"127 onChangeText={e => onChangeText('email', e)}128 value={state.email}129 isError={state.errors.email.isError}>130 <HelperText131 type="error"132 theme={{ colors: { error: color.yellow } }}133 visible={state.errors.email.isError}>134 {state.errors.email.message}135 </HelperText>136 </BaseTextInput>137 </View>138 <View style={styles.signUpFormControl}>139 <BaseTextInput140 mode="outlined"141 label="Password"142 secureTextEntry={!state.showPassword}143 isError={state.errors.password.isError}144 onChangeText={e => onChangeText('password', e)}145 iconPosition="right"146 icon={147 <TextInput.Icon148 name={state.iconPassword}149 color={color.grayLine}150 onPress={() => _handleTogglePassword()}151 />152 }>153 <HelperText154 type="error"155 theme={{ colors: { error: color.yellow } }}156 visible={state.errors.password.isError}>157 {state.errors.password.message}158 </HelperText>159 </BaseTextInput>160 </View>161 </View>162 <View style={styles.signUpButton}>163 <View>164 <BaseButton165 mode="contained"166 uppercase={false}167 size="medium"168 onPress={() => _handleSubmitRegister()}>169 Register170 </BaseButton>171 <Text172 onPress={() => navigation.navigate('SignIn')}173 style={styles.textInformation}>174 Already have account? <Text>Sign In Now</Text>175 </Text>176 </View>177 <ActivityIndicator178 size={36}179 animating={authReducer.isLoading}180 color={color.white}181 />182 </View>183 <Snackbar184 visible={authReducer.isError}185 duration={700}186 onDismiss={() => ({})}187 action={{188 label: 'Close',189 onPress: () => {190 dispatch(clearErrorAuth());191 },192 }}>193 <Text>{authReducer.errorMessages}</Text>194 </Snackbar>195 </View>196 );197};198export default SignUpScreen;199const styles = StyleSheet.create({200 container: {201 flex: 1,202 marginHorizontal: 16,203 },204 signUpTitleWrapper: {205 marginTop: 24,206 },207 signUpTitleHeadingText: fontConfig.fontStylesheet.h5,208 signUpTitleSubHeadingText: fontConfig.fontStylesheet.body1,209 signUpFormWrapper: {210 marginVertical: 24,211 },212 signUpFormControl: {213 marginBottom: 5,214 },215 signUpButton: {216 height: 160,217 flexDirection: 'column',218 justifyContent: 'space-between',219 },220 textInformation: {221 ...fontConfig.fontStylesheet.body2,222 color: color.yellow,223 marginTop: 18,224 textAlign: 'center',225 },...
CustomValidators.js
Source:CustomValidators.js
1// used to check if the given field is required2export const validateRequired = (inputValue) => {3 return inputValue.trim() === '';4};5// used to validate the minLength of the given field6export const validateMinLength = (inputValue, number) => {7 let isError = false;8 if (inputValue.trim().length === 0) {9 isError = false;10 } else if (inputValue.trim().length < number) {11 isError = true;12 }13 return isError;14};15// used to validate the maxLength of the given field16export const validateMaxLength = (inputValue, number) => {17 let isError = false;18 if (inputValue.trim().length === 0) {19 isError = false;20 } else if (inputValue.trim().length > number) {21 isError = true;22 }23 return isError;24};25// used to validate the given url26export const validateUrl = (inputValue) => {27 let isError = false;28 if (inputValue.trim().length === 0) {29 isError = false;30 } else if (31 !/^(https?:\/\/)?(www.)[a-z0-9]+(\.[a-z]{2,}){1,3}(#?\/?[a-zA-Z0-9#]+)*\/?(\?[a-zA-Z0-9-_]+=[a-zA-Z0-9-%]+&?)?$/.test(32 inputValue.trim()33 )34 ) {35 isError = true;36 }37 return isError;38};39// used to validate regEx40export const validateRegEx = (inputValue, regEx) => {41 let isError = false;42 if (inputValue.trim().length === 0) {43 isError = false;44 } else if (!regEx.test(inputValue.trim())) {45 isError = true;46 }47 return isError;48};49// used to check if number50export const validateNumber = (inputValue) => {51 let isError = false;52 if (inputValue.trim().length === 0) {53 isError = false;54 } else if (!/^[0-9]*$/.test(inputValue.trim())) {55 isError = true;56 }57 return isError;58};59// used to check if character60export const validateChar = (inputValue) => {61 let isError = false;62 if (inputValue.trim().length === 0) {63 isError = false;64 } else if (!/^[a-zA-Z\s]*$/.test(inputValue.trim())) {65 isError = true;66 }67 return isError;68};69// used to check alpha numeric with dots (.)70export const validateAlphaNumeric = (inputValue) => {71 let isError = false;72 if (inputValue.trim().length === 0) {73 isError = false;74 } else if (!/^[a-zA-Z0-9.]*$/.test(inputValue.trim())) {75 isError = true;76 }77 return isError;78};79export const validateEmail = (inputValue) => {80 let isError = false;81 if (inputValue.trim().length === 0) {82 isError = false;83 } else if (84 !/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(85 inputValue.trim()86 )87 ) {88 isError = true;89 }90 return isError;91};92// used to validate link93export const validateLink = (inputValue) => {94 let isError = false;95 if (inputValue.trim().length === 0) {96 isError = false;97 } else if (98 !/(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})/.test(99 inputValue.trim()100 )101 ) {102 isError = true;103 }104 return isError;...
is.js
Source:is.js
1"use strict";2var assert = require("chai").assert3 , isError = require("../../error/is");4describe("error/is", function () {5 it("Should return true on error", function () { assert.equal(isError(new Error()), true); });6 it("Should return false on native error with no common API exposed", function () {7 var value = new Error();8 value.message = null;9 assert.equal(isError(value), false);10 });11 it("Should return false on Error.prototype", function () {12 assert.equal(isError(Error.prototype), false);13 });14 if (typeof Object.create === "function") {15 it("Should return true on custom built ES5 era error", function () {16 var CustomEs5Error = function () { Error.call(this); };17 CustomEs5Error.prototype = Object.create(Error.prototype);18 assert.equal(isError(new CustomEs5Error()), true);19 });20 it("Should return false on object with no prototype", function () {21 assert.equal(isError(Object.create(null)), false);22 });23 }24 it("Should return false on plain object", function () { assert.equal(isError({}), false); });25 it("Should return false on function", function () {26 assert.equal(isError(function () { return true; }), false);27 });28 it("Should return false on array", function () { assert.equal(isError([]), false); });29 it("Should return false on string", function () { assert.equal(isError("foo"), false); });30 it("Should return false on empty string", function () { assert.equal(isError(""), false); });31 it("Should return false on number", function () { assert.equal(isError(123), false); });32 it("Should return false on NaN", function () { assert.equal(isError(NaN), false); });33 it("Should return false on boolean", function () { assert.equal(isError(true), false); });34 if (typeof Symbol === "function") {35 it("Should return false on symbol", function () {36 assert.equal(isError(Symbol("foo")), false);37 });38 }39 it("Should return false on null", function () { assert.equal(isError(null), false); });40 it("Should return false on undefined", function () { assert.equal(isError(void 0), false); });...
isError.test.js
Source:isError.test.js
...12describe('isError', function () {13 it('should return `true` for error objects', function () {14 var expected = map(errors, stubTrue);15 var actual = map(errors, function (error) {16 return isError(error) === true;17 });18 assert.deepStrictEqual(actual, expected);19 });20 it('should return `true` for subclassed values', function () {21 assert.strictEqual(isError(new CustomError('x')), true);22 });23 it('should return `false` for non error objects', function () {24 var expected = map(falsey, stubFalse);25 var actual = map(falsey, function (value, index) {26 return index ? isError(value) : isError();27 });28 assert.deepStrictEqual(actual, expected);29 assert.strictEqual(isError(args), false);30 assert.strictEqual(isError([1, 2, 3]), false);31 assert.strictEqual(isError(true), false);32 assert.strictEqual(isError(new Date()), false);33 assert.strictEqual(isError(_), false);34 assert.strictEqual(isError(slice), false);35 assert.strictEqual(isError({ 'a': 1 }), false);36 assert.strictEqual(isError(1), false);37 assert.strictEqual(isError(/x/), false);38 assert.strictEqual(isError('a'), false);39 });40 it('should return `false` for plain objects', function () {41 assert.strictEqual(isError({ 'name': 'Error', 'message': '' }), false);42 });...
Using AI Code Generation
1const unexpected = require('unexpected');2const unexpectedSinon = require('unexpected-sinon');3const sinon = require('sinon');4const expect = unexpected.clone().use(unexpectedSinon);5const test = require('tape');6test('Testing isError method of unexpected', function(t) {7 t.plan(1);8 const stub = sinon.stub().throws(new Error('Some Error'));9 try {10 stub();11 } catch (err) {12 expect(err, 'to be an error');13 }14 t.end();15});16const unexpected = require('unexpected');17const unexpectedSinon = require('unexpected-sinon');18const sinon = require('sinon');19const expect = unexpected.clone().use(unexpectedSinon);20const test = require('tape');21test('Testing message method of unexpected', function(t) {22 t.plan(1);23 const stub = sinon.stub().throws(new Error('Some Error'));24 try {25 stub();26 } catch (err) {27 expect(err, 'to have message', 'Some Error');28 }29 t.end();30});31const unexpected = require('unexpected');32const unexpectedSinon = require('unexpected-sinon');33const sinon = require('sinon');34const expect = unexpected.clone().use(unexpectedSinon);35const test = require('tape');36test('Testing match method of unexpected', function(t) {37 t.plan(1);38 const stub = sinon.stub().throws(new Error('Some Error'));39 try {40 stub();41 } catch (err) {42 expect(err, 'to have message', /Some/);43 }44 t.end();45});
Using AI Code Generation
1const expect = require('unexpected')2 .clone()3 .use(require('unexpected-sinon'));4describe('test', () => {5 it('should throw an error', () => {6 expect(() => {7 throw new Error('Error');8 }, 'to throw', 'Error');9 });10});11 expected [Function] to throw an error satisfying { message: 'Error' }12 expected [Function] to throw an error satisfying { message: Error }13 expected [Function] to throw an error satisfying { message: 'Error' }14 expected [Function] to throw an error satisfying { message: Error }15 expected [Function] to throw an error satisfying { message: 'Error' }16 expected [Function] to throw an error satisfying { message: Error }17 expected [Function] to throw an error satisfying { message: 'Error' }18 expected [Function] to throw an error satisfying { message: Error }19 expected [Function] to throw an error satisfying { message: 'Error' }20 expected [Function] to throw an error satisfying { message: Error }21 expected [Function] to throw an error satisfying { message: 'Error' }22 expected [Function] to throw an error satisfying { message: Error }23 expected [Function] to throw an error satisfying { message: 'Error' }24 expected [Function] to throw an error satisfying { message: Error }25 expected [Function] to throw an error satisfying { message: 'Error' }26 expected [Function] to throw an error satisfying { message: Error }27 expected [Function] to throw an error satisfying { message: 'Error' }28 expected [Function] to throw an error satisfying { message: Error }29 expected [Function] to throw an error satisfying { message: 'Error' }30 expected [Function] to throw an error satisfying { message: Error }31 expected [Function] to throw an error satisfying { message: 'Error' }32 expected [Function] to throw an error satisfying { message: Error }33 expected [Function] to throw an error satisfying { message: 'Error' }34 expected [Function] to throw an error satisfying { message: Error }
Using AI Code Generation
1const unexpected = require('unexpected');2const unexpectedSinon = require('unexpected-sinon');3const unexpectedPromise = require('unexpected-promise');4const sinon = require('sinon');5const expect = unexpected.clone().use(unexpectedSinon).use(unexpectedPromise);6const { stub } = sinon;7const { isError } = require('util');8const { add } = require('./add');9describe('add', () => {10 it('should add two numbers', () => {11 expect(add(1, 2), 'to equal', 3);12 });13 it('should throw an error if first argument is not a number', () => {14 expect(() => add('1', 2), 'to throw', 'first argument must be a number');15 });16 it('should throw an error if second argument is not a number', () => {17 expect(() => add(1, '2'), 'to throw', 'second argument must be a number');18 });19 it('should throw an error if both arguments are not numbers', () => {20 expect(() => add('1', '2'), 'to throw', 'arguments must be numbers');21 });22 it('should throw an error if first argument is not a number', () => {23 const error = new Error('first argument must be a number');24 expect(() => add('1', 2), 'to throw', error);25 });26 it('should throw an error if second argument is not a number', () => {27 const error = new Error('second argument must be a number');28 expect(() => add(1, '2'), 'to throw', error);29 });30 it('should throw an error if both arguments are not numbers', () => {31 const error = new Error('arguments must be numbers');32 expect(() => add('1', '2'), 'to throw', error);33 });34 it('should throw an error if first argument is not a number', () => {35 const error = new Error('first argument must be a number');36 expect(() => add('1', 2), 'to throw', isError(error));37 });38 it('should throw an error if second argument is not a number', () => {39 const error = new Error('second argument must be a number');40 expect(() => add(1, '2'), 'to throw', isError(error));41 });
Using AI Code Generation
1var unexpected = require('unexpected');2var expect = unexpected.clone();3var err = new Error('Error');4expect(err, 'to be an error');5expect(err, 'to be an error', 'Error');6expect(err, 'to be an error', 'Error', 'Error message');7var chai = require('chai');8chai.use(require('chai-as-promised'));9var assert = chai.assert;10var err = new Error('Error');11assert.isError(err);12assert.isError(err, 'Error');13assert.isError(err, 'Error', 'Error message');14var should = require('should');15var err = new Error('Error');16err.should.be.an.Error();17err.should.be.an.Error('Error');18err.should.be.an.Error('Error', 'Error message');19var expect = require('expect');20var err = new Error('Error');21expect(err).toBeA(Error);22expect(err).toBeA(Error, 'Error');23expect(err).toBeA(Error, 'Error', 'Error message');24var assert = require('assert');25var err = new Error('Error');26assert(err instanceof Error);27assert(err instanceof Error, 'Error');28assert(err instanceof Error, 'Error', 'Error message');29var err = new Error('Error');30expect(err).toBeInstanceOf(Error);31expect(err).toBeInstanceOf(Error, 'Error');32expect(err).toBeInstanceOf(Error, 'Error', 'Error message');33var assert = require('assert');34var err = new Error('Error');35assert(err instanceof Error);36assert(err instanceof Error, 'Error');37assert(err instanceof Error, 'Error', 'Error message');38var should = require('should');39var err = new Error('Error');40err.should.be.an.Error();41err.should.be.an.Error('Error');42err.should.be.an.Error('Error', 'Error message');43var expect = require('expect');44var err = new Error('Error');45expect(err).toBeA(Error);46expect(err).toBeA(Error, 'Error');47expect(err).toBeA(Error, 'Error', 'Error message');
Using AI Code Generation
1const expect = require('unexpected')2 .clone()3 .use(require('unexpected-http'));4});5 expected { Object (statusCode, body) } to deeply equal { Object (statusCode, body) }6const expect = require('unexpected')7 .clone()8 .use(require('unexpected-http'));9});10const expect = require('unexpected')11 .clone()12 .use(require('unexpected-http'));13describe('REST API', () => {14 it('should return a
Using AI Code Generation
1const expect = require('unexpected')2 .clone()3 .use(require('unexpected-sinon'));4describe('test', () => {5 it('test', () => {6 expect(function () {7 throw new Error('error');8 }, 'to throw', 'error');9 });10});11 0 passing (5ms)12 at Context.it (test.js:9:14)
Using AI Code Generation
1const expect = require('unexpected')2 .clone()3 .use(require('unexpected-sinon'));4const sinon = require('sinon');5const {add} = require('./add');6describe('add', () => {7 it('should return sum of two numbers', () => {8 expect(add(2, 3), 'to equal', 5);9 });10 it('should return sum of two numbers', () => {11 expect(add(2, 3), 'to equal', 5);12 });13 it('should return sum of two numbers', () => {14 expect(add(2, 3), 'to equal', 5);15 });16});17function add(a, b) {18 return a + b;19}20module.exports = {add};
Using AI Code Generation
1const { isError } = require('unexpected');2const { expect } = require('chai');3const { AssertionError } = require('assert');4describe('isError', () => {5 it('should return true for AssertionError', () => {6 expect(isError(new AssertionError())).to.be.true;7 });8 it('should return true for Error', () => {9 expect(isError(new Error())).to.be.true;10 });11 it('should return true for TypeError', () => {12 expect(isError(new TypeError())).to.be.true;13 });14 it('should return true for RangeError', () => {15 expect(isError(new RangeError())).to.be.true;16 });17});18const { isError } = require('unexpected');19const { expect } = require('chai');20const { AssertionError } = require('assert');21describe('isError', () => {22 it('should return true for AssertionError', () => {23 expect(isError(new AssertionError())).to.be.true;24 });25 it('should return true for Error', () => {26 expect(isError(new Error())).to.be.true;27 });28 it('should return true for TypeError', () => {29 expect(isError(new TypeError())).to.be.true;30 });31 it('should return true for RangeError', () => {32 expect(isError(new RangeError())).to.be.true;33 });34});35const { isError } = require('unexpected');36const { expect } = require('chai');37const { AssertionError } = require('assert');38describe('isError', () => {39 it('should return true for AssertionError', () => {40 expect(isError(new AssertionError())).to.be.true;41 });42 it('should return true for Error', () => {43 expect(isError(new Error())).to.be.true;44 });45 it('should return true for TypeError', () => {46 expect(isError(new TypeError())).to.be.true;47 });48 it('should return true for RangeError', () => {49 expect(isError(new RangeError())).to.be.true;50 });51});52const { isError } = require('unexpected');53const { expect } = require('chai');54const { AssertionError } = require('assert');55describe('isError', () => {56 it('should
Using AI Code Generation
1var unexpected = require('unexpected'),2 expect = unexpected.clone();3var err = new Error('some error');4expect(err, 'to be an error');5var unexpected = require('unexpected'),6 expect = unexpected.clone();7var err = new Error('some error');8expect(err, 'to be an error');9var unexpected = require('unexpected'),10 expect = unexpected.clone();11var err = new Error('some error');12expect(err, 'to be an error');13var unexpected = require('unexpected'),14 expect = unexpected.clone();15var err = new Error('some error');16expect(err, 'to be an error');17var unexpected = require('unexpected'),18 expect = unexpected.clone();19var err = new Error('some error');20expect(err, 'to be an error');21var unexpected = require('unexpected'),22 expect = unexpected.clone();23var err = new Error('some error');24expect(err, 'to be an error');25var unexpected = require('unexpected'),26 expect = unexpected.clone();27var err = new Error('some error');28expect(err, 'to be an error');29var unexpected = require('unexpected'),30 expect = unexpected.clone();31var err = new Error('some error');32expect(err, 'to be an error');33var unexpected = require('unexpected'),34 expect = unexpected.clone();35var err = new Error('some error');36expect(err, 'to be an error');37var unexpected = require('unexpected'),38 expect = unexpected.clone();39var err = new Error('some error');40expect(err, 'to be an error');41var unexpected = require('unexpected'),42 expect = unexpected.clone();43var err = new Error('some error');44expect(err, 'to be an error');
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!