Reputation: 176
I have an input in Next, typescript. Maxlength does work but minlength doesn't work now. Does anyone how to validate this both?
Here's my code.
<input type="text" placeholder="text" required={true} minLength={2} maxLength={10} />
<button type="submit">Submit</button>
Upvotes: 4
Views: 9710
Reputation: 1616
I've got an obscure solution which may or may not relate to what the OP was experiencing.
In my case, the tooltip-like error wasn't showing for an invalid minLength
value because I had applied .toUpperCase()
on the state, like so:
// PROBLEM
<input
required
name="guess-input"
type="text"
value={guess}
minLength={5}
maxLength={5}
onChange={(event) => {
const nextGuess = event.target.value.toUpperCase(); //<-- the culprit
setGuess(nextGuess);
}}
></input>
Apparently, that won't validate letters that have been transformed to upper.
As a solution, I dropped that method and added a style attribute like so:
// SOLUTION
<input
required
name="guess-input"
type="text"
value={guess}
minLength={5}
maxLength={5}
style={{ textTransform: "uppercase" }}
onChange={(event) => {
const nextGuess = event.target.value;
setGuess(nextGuess);
}}
></input>
Not shown is the rest of the markup for the form.
And in a function outside of the return, I passed set another variable equal to state and converted what it received. Because strings are immutable, I wouldn't have to worry about any mutation issues for state.
Here's that function:
function handleSubmit(event) {
event.preventDefault(); // prevent a submitted form from reloading the page
let upperGuess = guess.toUpperCase; // new pointer to an upper version of state
console.log({ upperGuess }); // see the new upper version
setGuess(""); // reset the input to empty
}
References:
Upvotes: 0
Reputation: 542
use can install Material ui Libraries npm install @material-ui/core
Material ui Libraries
There have lots of components. use Textfield components .
Using inputProps we set maxlength in textfield
<TextField inputProps={{ maxLength: 10 }} type="text" />
Material Ui Textfied Compoents
Upvotes: 2
Reputation: 275819
Your code is fine. However minlength
works different than maxlength
.
maxlength
prevents the user from typing keys more than the maxlength.minlength
will let the user enter less keys compared to the requirement. After all, they need to be able to start from less chars to come up to more chars. That said the field will show an error if minlenght is not met.Use this component and press the enter key to play around with the input field:
export default function App() {
return (
<form>
<input type="text" placeholder="text" required={true} minLength={2} maxLength={10} />
<button type="submit">Submit</button>
</form>
);
}
Upvotes: 3