3

I've searched all over the internet that how to form validate data sent by Angular js $http POST request in codeigniter.

For clear understanding I've posted completed HTML data. I believe that most of the developer are looking for this solution.

Here is my HTML Form:

<!DOCTYPE html>
<html>
    <head>
        <style>
            input[type="text"].ng-invalid{border: 1px solid red; }
        </style>
    </head>
    <body ng-app="app" ng-controller="ctrl">

        <form name="test_form" ng-submit="send_data()">
            <input type="text" name="email" ng-model="email">
            <span ng-show="test_form.email.$invalid - required">Required</span>

            <input type="password" name="password" ng-model="password">
            <span ng-show="test_form.email.$invalid - required">Required</span>

            <button type="submit">Submit</button>
        </form>


        <script src="<?php echo base_url('assets/angular/angular.min.js'); ?>" type="text/javascript">
        </script>
        <script>
                    angular.module('app', [])
                    .controller('ctrl', function ($scope, $http) {
                        $scope.send_data = function () {
                            $http({
                                method: "POST",
                                url: "<?php echo base_url('login/test_angular_validate'); ?>",
                                data: {email: $scope.email, password: $scope.password},
                                headers : {'Content-Type': 'application/x-www-form-urlencoded'}
                            }).then(function (success) {
                                console.log(success);
                            }, function (error) {

                            })
                        }
                    });
        </script>
    </body>
</html>

Backend Codeigniter Login Controller Function

<?php
public function test_angular_validate() {
    $form_data = json_decode(file_get_contents("php://input"), true);

    $this->load->helper(array('form', 'url'));

    $this->load->library('form_validation');

    $this->form_validation->set_rules('email', 'email', 'required|min_length[3]');
    $this->form_validation->set_rules('password', 'password', 'required');

    if ($this->form_validation->run() == FALSE) {
        echo 'failed';
        print_r(validation_errors());
    } else {
        echo 'success';
    }
}
?>

When is send html form data using angular $http POST request I'm unable to validate that data using codeigniter form validation library. It throws an validation error as given in this image.

lin
  • 17,956
  • 4
  • 59
  • 83
Pavan Webbeez
  • 219
  • 3
  • 12
  • think that codeigniter needs to have `$_POST['email']` and `$_POST['password']` values to be set before you can use codeigniter form validation.. i advise you to write a codeigniter helper function to convert the json data into $_POST array values... atleast try it hardcored in your code first to make sure `$_POST['email'] = 'test@hotmail.com'; $_POST['password'] = 'password';` before you load the form helper – Raymond Nijland Feb 18 '18 at 14:02

2 Answers2

2

Codeigniter access the super global $_POST for its validation. Your JSON data is not binded to this superglobal. So you need to set it up manually:

$_POST = json_decode(file_get_contents("php://input"), true);

You can also POST your data URLENCODED. In that way you your POST params will be available in $_POST without a manually set.

$http({
    method: 'POST',
    url: "<?php echo base_url('login/test_angular_validate'); ?>",
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    data: {
        email: $scope.email, 
        password: $scope.password
    },
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
}).then(function (success) {
    console.log(success);
}, function (error) {

});
lin
  • 17,956
  • 4
  • 59
  • 83
0

As you are using Codeigniter form validation libray, you'd better to convert your request data to an array as following:

$objectRequest = json_decode( file_get_contents("php://input") );
$this->request = xss_clean(json_decode(json_encode($objectRequest), true));

Also you don't need to use set_rules function for each data, instead you can manage them in config/form_validation.php file as mentioned here.

Here is a sample in form_validation.php :

$config = [

    'user_config' => [
        [
            'field' => 'user[phone]',
            'rules' => 'required|numeric|max_length[100]|min_length[10]'
        ],
        [
            'field' => 'user[phoneCode]',
            'rules' => 'required|numeric'
        ]
    ],
];

Then in your code:

if ( !$this->form_validation->run('user_config') ) exit();

Just you need to have corresponding names in Angularjs forms (ng-model)

Example:

<span class="form_row">
    <input ng-model="login.user.phoneCode" name="phoneCode" ng-required="true" ng-pattern="mobileCodePattern" size="6" type="text">
</span>
<span class="form_row">
    <input ng-model="login.user.phone" name="phone" ng-required="true" ng-pattern="numberOnly" type="text">
</span>

And send $scople.login to server.

Vahid Najafi
  • 4,654
  • 11
  • 43
  • 88