Validating a single page post
PermalinkI just need to ensure a few inputs have values before the single page gets posted.
Should I use javascript, or can I do this from a controller?
Where cheated validation could lead to a security breach of failure beyond the page itself, then you need to vaidate on the server.
//Validate $('.quick-events-add-event').submit(function(event) { var dates = 0; var errorMessage = ''; $('.start-selectors').each(function(index) { var startDate = $(this).find('.quick-event-date-selector').val(); if ( startDate.length > 0 ) { dates++; } else { var itemNumber = index + 1; errorMessage = errorMessage + '<span>' + '<?=t('Please add start date to date entry')?> #' + itemNumber + '</span>'; } }); var eventName = $('#eventName').val(); if ( eventName ) {
This is a quick (untested) trivial example I have just cooked up.
function save(){ if(!$this->post('my_text')){ $this->error->add(t("My Text is required. You cant leave it empty.")); } // // .... more validation // if (!$this->error->has()) { // actually save the post data // ... // and confirm success $this->set('success', t('It worked, your data has been saved')); // also works with 'message' } }
(Likely to be another case of everyone inventing their own way because the provided way isn't clearly documented)
Is this a single page available to the public or a dashboard single page? I ask because it may affect how you validate and sanitize the input.
It is common to see front end and back end validation used together. Front end validation using JavaScript should not be used in place of back end validation, due to it being easier to bypass - back end validation is always required.
In dashboard single pages, I believe you can use $this->error. It is made available for use in the DashboardPageController class using the validation/error helper service which creates an Concrete\Core\Error\Error object.
https://github.com/concrete5/concrete5/blob/develop/concrete/src/Pag...
With the error object, you can use methods like add(), has(), getList(), output().
In single pages, I believe you have to create your own error object.
5.7:
- import Application
use Concrete\Core\Support\Facade\Application;
- create and use your error object
In 5.8, I believe $this->app is available without importing Application:
There are many variations and ways to do this, this is just one.