Currently i am using Angular JS and using form validation as below:
<div class="form-group" ng-class="{ 'has-error' : validating && form.name.$invalid }">
<label for="name" class="col-md-3 control-label">Name</label>
<div class="col-md-9">
<input type="text" id="name" name="description" ng-model="name" class="form-control" required />
</div>
</div>
So basically if Name is not populated the form is invalid.
Is there an equivalent way in ReactJS ?
3
Answers
The HTML attribute
required
will work in react jsx component also. If you require to add more validations like length of name or check any special chars, you can store the input field value in a state usinguseState
hook and check manually while submitting.Of course, you can do that. The easiest way is to use third party library such as
react-hook-form
.For example:
This way, you can implement validation in the form.
To learn more, please see React Hook Form Documentation.
For simple form, you can handle it manually using
useState
, demoBut for complicated form you can use 3rd party like react-hook-form to handle form. It has some features like watch the field change, schema validate…:
Demo