Search code examples
phpcssformstextboxlive

Validating input field on exit of field pure PHP


I'm trying to create an system that can calculate all input given for invoice related calculating.

What I'm trying to achieve is when I have multiple text fields (Yes I want to use text fields otherwise I would have used the build in validator for the number field)

So when I click out of a text box it needs to validate live if the input is numeric. and when its not it should show some message above it that it isn't and make the field red like an error. BEFORE submitting the form

And yes I know this is easily done with jQuery/ajax/php setups but I want to only use PHP. So IS there some kind of way to do this pure PHP or not because I can't seem to find some way or tutorial that does this.

Sorry if this question is shit but I'm at wits end now searched for 2 hours straight and cant even come close to finding some way that uses only PHP.

I'm using an hidden div and going to use style tags that only show when input is wrong so the errors/red colors are already done now I just need some kind of validator

Thanks in advance and again I'm sorry if this is a shitty question


Solution

  • If you want the validation on server-side in PHP you need to use either a ajax request on each click and send the data, or do the following before you echo or output anything, for example if your model or controller...Iterate on your data and run this regex rule on each of your values:

    if( preg_match('/^[1-9]\d*(\,\d+)?$/', $inputValue ) ) {
    // It is numeric
    }
    else{
    // It is not numeric
    }
    

    I assume you use . as your decimal operator? If no, the rule should be:

    preg_match(^[1-9]\d*(\,\d+)?$)
    

    This will tell you if it's numeric.

    Note that the $inputValue is the variable you are testing.