# new RequiredValidator(messageopt)
The RequiredValidator ensures that a value is provided and not empty. It handles different types of values appropriately: for booleans and numbers, it checks if they're undefined; for other types (strings, arrays, objects), it checks if they're falsy. This validator is typically used with the @required decorator and is often the first validation applied to important fields.
Validator for checking if a value is present and not empty
Parameters:
Name | Type | Attributes | Description |
---|---|---|---|
message |
string
|
<optional> |
Custom error message to display when validation fails, defaults to |
Example
```typescript
// Create a required validator with default error message
const requiredValidator = new RequiredValidator();
// Create a required validator with custom error message
const customRequiredValidator = new RequiredValidator("This field is mandatory");
// Validate different types of values
requiredValidator.hasErrors("Hello"); // undefined (valid)
requiredValidator.hasErrors(""); // Returns error message (invalid)
requiredValidator.hasErrors(0); // undefined (valid - 0 is a valid number)
requiredValidator.hasErrors(null); // Returns error message (invalid)
requiredValidator.hasErrors([]); // undefined (valid - empty array is still an array)
```
Extends
Methods
# hasErrors(value, optionsopt) → {string|undefined}
Validates that the provided value exists and is not empty. The validation logic varies by type:
- For booleans and numbers: checks if the value is undefined
- For other types (strings, arrays, objects): checks if the value is falsy
Checks if a value is present and not empty
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
value |
any
|
The value to validate |
||
options |
ValidatorOptions
|
<optional> |
{} | Optional configuration options |
- Overrides:
- See:
View Source validation/Validators/RequiredValidator.ts, line 125
Error message if validation fails, undefined if validation passes
string
|
undefined