1

This is the field in the admin side form which is ment to be required.

<field name="exam_name" 
type="text"
label="Name"
required="true" />

In the form if I leave this field empty (null) then it shows a validation error Invalid Field.

But if I leave a space then it submits the page and space stored in the database.

Is there a way to validate the form even a particular field is having space instead of empty?

1

You could use client side validation. So firstly, add the following to the form view (Choose one depending on your Joomla version)

JHtml::_('behavior.formvalidation'); // Joomla 3.3
JHtml::_('behavior.formvalidator');  // Joomla 3.4

Then add the form-validate class to your form so it looks like this:

<form class="form-validate">

Then add the required classes to your form field like so:

<field name="exam_name" class="required validate-custom"

Then apply the same to your form submit button, like so:

<input type="submit" class="required validate-custom"

And finally, you can use the following jQuery:

jQuery(document).ready(function($){
    document.formvalidator.setHandler('custom', function (value) {
        // Perform your validation for blank spaces
        // You could use a regex or maybe trim the value
        // Whatever method you prefer
    });
});
  • thanks for this. Sorry I didn't mention in the question correctly. I am trying this from admin side. Is this answer still apply for admin side validation? – Malaiselvan Apr 22 '15 at 10:22
  • Yes, it will still work. Please note I haven't actually tested this as there may be some minor tweaks you'll have to make – Lodder Apr 22 '15 at 10:29
  • Thanks for explaining the custom handler. How can I do this with XML form fields?? Meaning I use the joomla renderField to display the field. How can I add the custom validation handler in this case? – Malaiselvan Nov 14 '15 at 11:11
  • 1
    Client side validation never replaces server side validation... – inf3rno Feb 26 '17 at 12:39
1

If your model extends JModelAdmin or JModelForm, you can use its validate function to validate client input before saving it to database.

class MyComponentModelForm extends JModelAdmin
{

  ....
  ....

  /* Override */
  public function validate($form, $data, $group = null)
  {
     $data = parent::validate($form, $data, $group = null);
     if(!$data || empty($data['myfield']))
     {
       JFactory::getApplication()->enqueueMessage(JText::_('COM_MYCOMPONENT_FIELD_REQUIRED'));
       return false;
     }

    return $data;
  }
}
  • setError is deprected. – Sahil Purav May 26 '15 at 11:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.