skip to Main Content

I’m just trying to add validation in my vuetify form from my Model or Controller and make an alert.

In my .vue file

<v-row dense>
    <v-col cols="3">
        <v-text-field dense outlined label="Employee Code" v-model="emp_code"></v-text-field>
    </v-col>
    <v-col cols="3">
        <v-text-field dense outlined label="Employee Name" v-model="emp_name"></v-text-field>
    </v-col>
    <v-col cols="2">
        <v-text-field dense outlined label="Age" v-model="emp_age"></v-text-field>
    </v-col>
    <v-col cols="2">
        <v-btn @click="Insert()">Insert</v-btn>
    </v-col>
</v-row>

And this is what it looks like:

In my script, I have this data

data: () => ({
    emp_code:null,
    emp_name:null,
    emp_age:null,
}),

And my methods is:

methods: {
    Insert(){
        axios.post('api/employees', {
                emp_code:this.emp_code,
                emp_name:this.emp_name,
                emp_age:this.emp_age
            })
        .then(res => {
            console.log(res.data)
            this.emp_code = null
            this.emp_name = null
            this.emp_age = null
        })
    }
}

Controller.php:

public function store(Request $request)
    {
        $employee_data = $request->all();
        $employee_code = "12345";
        $employee_model = new EmployeeModel();
        DB::transaction(function() use($employee_model, $employee_data, $employee_code){
            $employee_model->InsertEmployee($employee_data, $employee_code);
        });
    }

I’m using DAO and DTO, so

Model.php:

public function InsertEmployee($employee_data, $employee_code){
    $employee_data['EmployeeCode'] = $employee_data['emp_code'];
    $employee_data['EmployeeName'] = $employee_data['emp_name'];
    $employee_data['Age'] = $employee_data['emp_age'];
    $employee_data['UpdatedBy'] = $employee_code;
    $dao_insert_employee = new DAO();
    $dao_insert_employee->InsertEmployee($employee_data, $employee_code);

DAO.php

public static function InsertEmployee($employee_data, $employee_code){
    DB::transaction(function() use($employee_data, $employee_code){
        Employee::insert(
            [
                'EmployeeCode' => $employee_data["emp_code"],
                'EmployeeName' => $employee_data["emp_name"],
                'Age' => $employee_data["emp_age"],
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
                'deleted_at' => null,
                'UpdatedBy' => $employee_code,
            ]
        );
    });
}

DTO.php

class DTO{
    public $EmployeeCode;
    public $EmployeeName;
    public $Age;
    public $deleted_at;

    /**
     * Get the value of EmployeeCode
     */ 
    public function getEmployeeCode()
    {
        return $this->EmployeeCode;
    }
    public function setEmployeeCode($EmployeeCode)
    {
        $this->EmployeeCode = $EmployeeCode;

        return $this;
    }
//Other codes here...

For now, I am able to insert data in my database, But I want to add a validator. I just want a simple alert in no data inputted on the TextField:

And I also want to validate the employee_code to it’s maxlength to 5 digit only, so if inputted data is 4 digit below or 6digit above, alert will show message like "Employee Code is 5 digit only".

  • I’m trying not to have a condition on my vue file or the validation on text-field like :maxlength='5'.
  • All I want is show the alert, if user input in the emp_code is letter, show alert('Employee Code must be a number.'), if user input in the emp_name is number, show alert('Employee Name must be a letter.'). If all fields are null, show alert('You must input all the fields.').

2

Answers


  1. Chosen as BEST ANSWER

    This is already answered by my friend from other country after i reached him. This is how he do it.

    Giving this MVC Model Flow enter image description here

    Home.vue

    <v-row dense>
                    <v-col cols="2">
                        <v-text-field dense outlined label="Employee Code" v-model="myObj.EmployeeCode"></v-text-field>
                    </v-col>
                    <v-col cols="3">
                        <v-text-field dense outlined label="Employee Name" v-model="myObj.EmployeeName"></v-text-field>
                    </v-col>
                    <v-col cols="2">
                        <v-text-field dense outlined label="Age" v-model="myObj.Age"></v-text-field>
                    </v-col>
                    <v-col cols="2">
                        <v-btn @click="Insert()">INSERT</v-btn>
                    </v-col>
                </v-row>
    

    mydata is...

    data(){
                return {
                    myObj:{
                        EmployeeCode: '',
                        EmployeeName: '',
                        Age: '',
                        EmployeeDeletedAt: '',
                    }
    

    Then, my method is...

     methods:{
            Insert(){
                    axios.post(`api/employees`,this.myObj)
                    .then(res => {
                        if(res.data instanceof Array){
                            console.log(res.data)
                            alert('Insert Successful!')
                        }else{
                            alert(res.data)
                        }
                    }).catch(({response}) => {
                        this.$router.push('/error/' + response.status)
                    })
                }
    }
    

    Controller.php

    public function store(Request $req)
        {
            try {
                $employee_model = new EmployeeModel();
                $employee_model->InsertEmployee($req);
                return $employee_model->EmployeeList();
            } catch(Exception $e) {
                $err_data = ['Parameters' => $req, 'Functions' => __FUNCTION__];
                throw new CommonException($e, $err_data, 500);
            }
        }
    

    Model.php

    public function InsertEmployee($req){
            $dao_employee = new DAO();
            $existing = $dao_employee::ExistingEmployeeCode($req->input('EmployeeCode'));
            if($existing){
                return 'Existing Employee Code!';
            }else if(trim($req->input('EmployeeCode')) == ''){
                return 'Please input employee code!';
            }else if(trim($req->input('EmployeeName')) == ''){
                return 'Please input employee name!';
            }else if(trim($req->input('Age')) == ''){
                return 'Please input age!';
            }else if(strlen(trim($req->input('EmployeeCode'))) != 5){
                return 'Employee code must be 5 characters only';
            }else if(!is_numeric(trim($req->input('Age')))){
                return 'Age must be number only';
            }else{
                DB::transaction(function () use($req, $dao_employee){
                    $dao_employee::InsertEmployee($req);
                });
            }
        }
    

    DAO.php

    public static function InsertEmployee($req){
            Employee::insert(
                [
                    'EmployeeCode' => $req->input('EmployeeCode'),
                    'EmployeeName' => $req->input('EmployeeName'),
                    'Age' => (int)$req->input('Age'),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                    'deleted_at' => null,
                    'UpdatedBy' => '12345'
                ]
            );
        }
    

    I hope this could help for future reference.


  2. You can add rules attribute on v-text-field tag to control fading validation.

    <v-text-field :rules="codeRules" dense outlined label="Employee Code" v-model="emp_code"></v-text-field>
    <v-text-field :rules="nameRules" dense outlined label="Employee Name" v-model="emp_name"></v-text-field>
    
    export default {
        data: () => ({
          firstName: '',
          codeRules: [
            value => {
              if (/^d+(.d+)?$/.test(value)) return true
              return 'Employee Code must be a number.'
            },
          ],
          nameRules: [
            value => {
              if (/^[A-Za-z]+$/.test(value)) return true
              return 'Employee Name must be a letter.'
            },
          ],
        }),
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search