Working with `redux-form` & `react-intl` and I am wondering what might you display to the user that the _message body_ is invalid. The code below is what I am displaying now, but it seems overkill and possibly bad to just come right out and say this is the regex I'm using (as my first line of defense) to protect my backend from getting some malicious garbage. Thoughts? Ideas?
// validate.js
import { messages } from '../../lib'
const messageRegex = /^[A-Za-z0-9.!?,;\s]+$/
export default (values, { intl }) => {
const errors = {}
if (!values.message) {
errors.message = intl.formatMessage(messages.errMessageReq)
} else if (values.message.length < 10) {
errors.message = intl.formatMessage(messages.errMessageMinLen)
} else if (values.message.length > 140) {
errors.message = intl.formatMessage(messages.errMessageMaxLen)
} else if (!messageRegex.test(values.message)) {
errors.message = intl.formatMessage(messages.errMessageVal)
}
return errors
}
// ./lib/messages.js
import { defineMessages } from 'react-intl'
const messages = defineMessages({
...
errMessageReq: {
id: 'messageRequired',
defaultMessage: 'Message is required.'
},
errMessageVal: {
id: 'messageInvalid',
defaultMessage:
'Invalid message. May only contain: A-Z, a-z, 0-9, ".", "!", "?", & ","'
},
errMessageMaxLen: {
id: 'messageMaxLength',
defaultMessage: 'Message must be not longer than 140 characters.'
},
errMessageMinLen: {
id: 'messageMinLength',
defaultMessage: 'Message must be at least 10 characters long.'
})
export { messages }
Jason Knight
The less code you use, the less there is to break
honestly I wouldn't be using JavaScript for this in the first place, since 1) HTML 5 offers perfectly good attributes for handling this without scripting, and 2) ANY such checks NEED to be re-performed again server-sides, so there is usually little LEGITIMATE reason to be wasting code client-side for this unless you've fallen into the "wah wah, teh pageloadz is teh evils" trap.
Though if this is full stack and the above IS the server side code, expecting the user to wildly GUESS what you expect for input is one of the most annoying things you can do. Why isn't this text shown ALL THE BLOODY TIME next to or near the input/textarea in question?!?
Oh wait, you're using frameworks that are redundant to just using HTML and CSS properly and in an accessible manner, that's why.
I would show the requirements in the field all the time, then give the textarea/input the appropriate attributes such as "required" all the time. The most I'd have the back-end do is add a class so that CSS can be used to style "hey look at me" and maybe just the word "error" or some such.