Lev berg
Lev berg

Reputation: 75

React form hook - validation, no Trailing or Leading or only white spaces for input value

I'm trying to create a validator in "react-hook-form": "^7.3.6" @typescript with @material-ui for cases that includes whitespace in the input field; for example, a user can enter " "/" username"/" username " and it will be a valid username.

I have tried several Regular expressions in the pattern field but didn't come up with the right one for what I'm looking for, or am I not approaching this the right way?

<TextField
    variant="outlined"
    margin="normal"
    required
    fullWidth
    id="username"
    label="Enter Username"
    name="username"
    autoFocus
    {...register("username",  {
        required: "required",
        minLength: {
            value: 3,
            message: "minimum number of character for username is 3"
        },
        pattern: {
            value: /\s/g,
            message: "Entered value cant start/end or contain only white spacing"
            },
        })}
        helperText={errors.username?.message}
    />

Upvotes: 4

Views: 11489

Answers (1)

Connor Low
Connor Low

Reputation: 7186

You probably want /^[^\s]+(?:$|.*[^\s]+$)/ for your regular expression, if you are trying to match valid inputs (/(?:^\s+|\s+$)/ will match the opposite, invalid inputs). /\s/g will catch any string that contains whitespace (e.g. match: "this string matches", no match: "this_string_doesn't").

Upvotes: 3

Related Questions