Introduction

OstroJS offers a variety of methods for validating incoming data in your application. The validate method, which is accessible on all incoming HTTP requests, is most commonly used. Other ways to validation, however, will be discussed as well.

OstroJS comes with a number of useful validation rules that you can use on data, including the ability to check if entries in a database table are unique. We'll go through each of these rules in depth so you're familiar with all of OstroJS's validation options.

Validation Quickstart

Let's take a look at a comprehensive example of validating a form and returning the error messages to the user to understand more about OstroJS's robust validation features. You'll be able to get a decent basic knowledge of how to validate incoming request data with OstroJS by reading this high-level overview:

Writing The Validation Logic

Now we can fill in the logic to validate the new blog post in our store function. We'll utilise the validate function offered by the @ostro/http/request object to do this. If the validation rules pass, your code will continue to run normally; however, if validation fails, an @ostro/validation/validationException exception will be produced, and the user will receive the appropriate error response.

A redirect response to the previous URL will be provided if validation fails during a standard HTTP request. If the inbound request is an XHR request, the validation error messages will be returned in a JSON response.

Let's go back to the store method to obtain a better grasp of the validate method:
 

/**
 * Store a new blog post.
 */
async store({ request }) {
    await request.validate({
        'title': 'required|unique:posts|max:255',
        'body': 'required',
    });

    // The blog post is valid...
}

The validation criteria are supplied into the validate function, as you can see. Don't worry; we've recorded all of the possible validation rules. If the validation fails, the appropriate response will be created automatically. Our controller will continue to run normally if the validation succeeds.

Instead of a single | delimited text, validation rules can be supplied as arrays of rules:

await request.validate({
    'title': ['required', 'unique:posts', 'max:255'],
    'body': ['required'],
});

Stopping On First Validation Failure

After the first validation failure, you may want to cease performing validation rules on an attribute. Assign the bail rule to the following attribute:

await request.validate({
    'title': 'bail|required|unique:posts|max:255',
    'body': 'required',
});

The max rule will not be tested in this case if the unique rule on the title property fails. The validation of rules will take place in the order in which they are allocated.

A Note On Nested Attributes

If the incoming HTTP request contains "nested" field data, you may use the "dot" syntax to indicate these fields in your validation rules:

await request.validate({
    'title': 'required|unique:posts|max:255',
    'author.name': 'required',
    'author.description': 'required',
});

If your field name, on the other hand, contains a literal period, you may avoid it being read as "dot" syntax by escaping the period with a backslash:

Displaying The Validation Errors

So, what if the fields in the incoming request don't pass the validation rules? OstroJS will instantly return the user to their previous location, as previously stated. In addition, any validation problems and request input will be flashed to the session automatically.

The @ostro/view/middleware/shareErrorsFromSession middleware, which is offered by the web middleware group, shares a $errors variable with all of your application's views. When you use this middleware, a $errors variable will always be present in your views, enabling you to safely assume that the $errors variable is always defined. The $errors variable will be an @ostro/support/messageBag object. Check out the documentation for further information on how to use this object.

When validation fails, the user will be routed to our controller's create function, allowing us to display the following error messages in the view:

<!-- /resources/views/post/create.html-->

<h1>Create Post</h1>

<% if(helpers.error.has('username')){ %>
    <div class="alert alert-danger">
        <ul>
            <% for(let error in helpers.error.all()){ %>
                <li><%= error %></li>
            <% } %>
        </ul>
    </div>
<% } %>

<!-- Create Post Form -->

Customizing The Error Messages

Each of OstroJS's built-in validation rules has an error message that can be found in the resources/lang/en/validation.js file of your application. There is a translation item for each validation rule in this file. You can update or modify these messages to fit your application's requirements.

You may also transfer this file to another translation language directory to translate the messages for the language of your application. Check out the whole OstroJS localization manual for additional information.

XHR Requests & Validation

We used a standard form to provide data to the programme in this example. Many programmes, on the other hand, get XHR queries via a JavaScript frontend. Laravel does not provide a redirect response when the validate method is used in an XHR request. Laravel instead sends a JSON response with all of the validation problems. The HTTP status code for this JSON response will be 422.

Available Validation Rules

accepteddigits_betweenregex
after (date)emailrequired
alphafilerequired_if
alpha_numfilledrequired_unless
alpha_dashinrequired_with
arrayintegerrequired_with_all
before (date)iprequired_without
betweenjsonrequired_without_all
booleanmaxsame
confirmedminsize
datenot_instring
differentnumericurl
digitspresent