I am making my own MVC framework and I was thinking of a way to do "automatic" client side validation controller.
Among other functionalities, my forms, elements and validators are objects that work together somewhat like this (inside the form object):
$this->addElement('text', 'myInput');
$this->elements['myInput']->addValidators(array
'length' => array('min' => 5, 'max' => 10),
'number' => array('decimals' => 0)
));
In the example above, I created a text input named 'myInput' whose value, according to the validators I added:
- Must be >= than 5 characters
- Must be <= than 10 characters
- Must be a number
- Must have no decimals (int only)
When I get the form submission and call a validation function, all works well on the server side. However, what bothered me was having to redo validation on the client side manually. I dislike having to duplicate the same functionality so I came up with a way to create my client side validation from the PHP form object that is already there.
It boils down to having JS validator functions that have the same functionality as the PHP validators and calling a getClientValidatiors() function on elements to create the appropriate <script>
in the body which attaches the JS events.
NOTE: Please ignore JS errors, I wrote this as a concept and didn't test anything just yet.
The JS validator functions would work like this:
function lengthValidator(options, value, id){
//Validate according to the options. Return true if valid or false otherwise as well as calling printError function with the message and the id
}
function numberValidator(options, value, id){
//Validate according to the options. Return true if valid or false otherwise as well as calling printError function with the message and the id
}
function printError(error, id){
//Might add more functionality later
document.getElementById(id).innerHTML = error;
}
For example, this is what it would look like in the view:
<?php echo $this->form->elements['myInput]; //The HTML ?>
<?php echo $this->form->elements['myInput]->getClientValidators(); //The JS ?>
Prior to form submission, the result would look like:
<input type="text" name="myInput" id="myInput"/>
<span class="error" id="myInput-error"></span>
<script>
document.getElementById('myInput').addEventListener('blur', function(e){
var value = e.value;
var id = e.id + '-error';
if(lengthValidator({min:5, max:10}, value, id) != true){
return;
}
if(numberValidator({decimals:0}, value, id) != true){
return;
}
});
</script>
I'm looking for a thumbs up or suggestions on how this could work with another technique. If you have any thoughts, I'd like to hear them!