article

Friday, February 11, 2022

Vue.js PHP Input Validation

Vue.js PHP Input Validation

Bootstrap 4.0 Version
https://getbootstrap.com/docs/4.0/getting-started/introduction/
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css

vuejs
https://v2.vuejs.org/v2/guide/installation.html
CDN : https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js

Axios  
https://www.npmjs.com/package/axios
CDN : https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
<title>Vue.js PHP Input Validation</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light navbar-cairocoders">
    <div class="container">
    <a class="navbar-brand" href="#">Cairocoders</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>

    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link" href="#">Login</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Register</a>
            </li>
        </ul>

    </div>
    </div>
</nav>

<main class="my-form" id="validate">
    <div class="cotainer">
        <div class="row justify-content-center">
            <div class="col-md-8"><h1 class="page-header text-center">Vue.js PHP Input Validation </h1>
                    <div class="card">
                        <div class="card-header">Register</div>
                        <div class="card-body">
						
							<div class="alert alert-success text-center" v-if="successMessage">
								<button type="button" class="close" @click="clearMessage();"><span aria-hidden="true">×</span></button>
								<span class="glyphicon glyphicon-check"></span> {{ successMessage }}
							</div>
                           
                                <div class="form-group row">
                                    <label class="col-md-4 col-form-label text-md-right">Username</label>
                                    <div class="col-md-6">
                                        <input type="text" ref="username" class="form-control" v-model="forValidation.username">
										<div v-if="errorUsername" class="error">{{ errorUsername }}</div>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label class="col-md-4 col-form-label text-md-right">Password</label>
                                    <div class="col-md-6">
                                        <input type="password" ref="password" class="form-control" v-model="forValidation.password">
										<div v-if="errorPassword" class="error">{{ errorPassword }}</div>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label class="col-md-4 col-form-label text-md-right">Firstname</label>
                                    <div class="col-md-6">
                                        <input type="text" ref="firstname" class="form-control" v-model="forValidation.firstname">
										<div v-if="errorFirstname" class="error">{{ errorFirstname }}</div>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label class="col-md-4 col-form-label text-md-right">Lastname</label>
                                    <div class="col-md-6">
                                        <input type="text" ref="lastname" class="form-control" v-model="forValidation.lastname">
										<div v-if="errorLastname" class="error">{{ errorLastname }}</div>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label class="col-md-4 col-form-label text-md-right">Email</label>
                                    <div class="col-md-6">
                                        <input type="text" ref="email" class="form-control" v-model="forValidation.email">
										<div v-if="errorEmail" class="error">{{ errorEmail }}</div>
                                    </div>
                                </div>

                                <div class="form-group row">
                                    <label class="col-md-4 col-form-label text-md-right">Website</label>
                                    <div class="col-md-6">
                                        <input type="text" ref="website" class="form-control" v-model="forValidation.website">
										<div v-if="errorWebsite" class="error">{{ errorWebsite }}</div>
                                    </div>
                                </div>

                                <div class="col-md-6 offset-md-4">
									<button class="btn btn-primary" @click="validateInput();"><span class="glyphicon glyphicon-check"></span> Validate</button>
                                </div>
                        </div>
                    </div>
            </div>
        </div>
    </div>
</div>
</main>
<script src="app.js"></script>
<style>
body{
    margin: 0;
    font-size: .9rem;
    font-weight: 400;
    line-height: 1.6;
    color: #212529;
    text-align: left;
    background-color: #f5f8fa;
}

.navbar-cairocoders
{
    box-shadow: 0 2px 4px rgba(0,0,0,.04);
}

.navbar-brand , .nav-link, .my-form, .login-form
{
    font-family: Raleway, sans-serif;
}

.my-form
{
    padding-top: 1.5rem;
    padding-bottom: 1.5rem;
}

.my-form .row
{
    margin-left: 0;
    margin-right: 0;
}

.login-form
{
    padding-top: 1.5rem;
    padding-bottom: 1.5rem;
}

.login-form .row
{
    margin-left: 0;
    margin-right: 0;
}
.error{
	font-size:13px;color:red;
}
</style>
</body>
</html>
app.js
//app.js
var app = new Vue({
	el: '#validate',
	data:{
		forValidation: {username: '', password: '', firstname:'', lastname:'', email:'', website:''},
		errorUsername: "",
		errorPassword: "",
		errorFirstname: "",
		errorLastname: "",
		errorEmail: "",
		errorWebsite: "",
		successMessage: ""
	},

	methods:{
		validateInput: function(){
			var valForm = app.toFormData(app.forValidation);
			axios.post('validate.php', valForm)
				.then(function(response){
					//console.log(response);
					if(response.data.username){
						app.errorUsername = response.data.message;
						app.focusUsername();
					}
					else if(response.data.password){
						app.errorPassword = response.data.message;
						app.errorUsername = '';
						app.focusPassword();
					}
					else if(response.data.firstname){
						app.errorFirstname = response.data.message;
						app.errorUsername = '';
						app.errorPassword = '';
						app.focuFirstname();
					}
					else if(response.data.lastname){
						app.errorLastname = response.data.message;
						app.errorUsername = '';
						app.errorPassword = '';
						app.errorFirstname = '';
						app.focusLastname();
					}
					else if(response.data.email){
						app.errorEmail = response.data.message;
						app.errorUsername = '';
						app.errorPassword = '';
						app.errorFirstname = '';
						app.errorLastname = '';
						app.focusEmail();
					}
					else if(response.data.website){
						app.errorWebsite = response.data.message;
						app.errorEmail = response.data.message;
						app.errorUsername = '';
						app.errorPassword = '';
						app.errorFirstname = '';
						app.errorLastname = '';
						app.errorEmail = '';
						app.focusWebsite();
					}
					else{
						app.successMessage = response.data.message;
						app.errorUsername = '';
						app.errorPassword = '';
						app.errorFirstname = '';
						app.errorLastname = '';
						app.errorEmail = '';
						app.errorWebsite = '';
					}
				});
		},

		focusUsername: function(){
			this.$refs.username.focus();
		},

		focusPassword: function(){
			this.$refs.password.focus();
		},

		focusFirstname: function(){
			this.$refs.firstname.focus();
		},

		focusLastname: function(){
			this.$refs.lastname.focus();
		},

		focusEmail: function(){
			this.$refs.email.focus();
		},

		focusWebsite: function(){
			this.$refs.website.focus();
		},

		toFormData: function(obj){
			var form_data = new FormData();
			for(var key in obj){
				form_data.append(key, obj[key]);
			}
			return form_data;
		},

		clearMessage: function(){
			app.successMessage = '';
		}

	}
});
validate.php
//validate.php
<?php

$out = array('username' => false, 'password' => false, 'firstname' => false, 'lastname' => false, 'email' => false, 'website' => false);

function check_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

$username=check_input($_POST['username']);
$password=check_input($_POST['password']);
$firstname=check_input($_POST['firstname']);
$lastname=check_input($_POST['lastname']);
$email=check_input($_POST['email']);
$website=check_input($_POST['website']);

if($username==''){
	$out['username']=true;
	$out['message']='Username is required';
}

elseif (!preg_match("/^[a-zA-Z_1-9]*$/",$username)) {
	$out['username']=true;
  	$out['message'] = "Only letters, numbers and underscore allowed"; 
}

elseif($password==''){
	$out['password']=true;
	$out['message']='Password is required';
}

elseif($firstname==''){
	$out['firstname']=true;
	$out['message']='Firstname is required';
}

elseif (!preg_match("/^[a-zA-Z ]*$/",$firstname)) {
	$out['firstname']=true;
  	$out['message'] = "Only letters and white space allowed"; 
}

elseif($lastname==''){
	$out['lastname']=true;
	$out['message']='Lastname is required';
}

elseif (!preg_match("/^[a-zA-Z ]*$/",$lastname)) {
	$out['lastname']=true;
  	$out['message'] = "Only letters and white space allowed"; 
}

elseif($email==''){
	$out['email']=true;
	$out['message']='Email is required';
}

elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  	$out['email']=true;
	$out['message']='Invalid Email Format';
}

elseif($website==''){
	$out['website']=true;
	$out['message']='Website is required';
}

elseif (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
  	$out['website']=true;
	$out['message']='Invalid URL';
}

else{
	$out['message']='Form Validated';
}

header("Content-type: application/json");
echo json_encode($out);
die();

?>

Related Post