Search code examples
reactjsyup

Required doesn't work after adding test Yup


This is what i've done

subject: Yup.string().test('checkForManualText', 'Please, add hand-written subject as well',
            function(inputValue) {
                let newMessage = inputValue.replace(/\{{(.+?)\}}/gmi, '').replace('/\s/gmi', '').trim()
                return newMessage.length !== 0
            }).required()

Now the test validation works fine, but the required stopped working. Before adding test, all was good.


Solution

  • You don't need to use required when using .test. Returning false will show the error message. Just add null/undefined check to the string.

    subject: Yup.string().test('checkForManualText', 'Please, add hand-written subject as well',
                function(inputValue) {
                    if(!inputValue) return false;
                    let newMessage = inputValue.replace(/\{{(.+?)\}}/gmi, '').replace('/\s/gmi', '').trim()
                    return newMessage.length !== 0
                })
    

    Working Example