简体   繁体   中英

How to clear jasny input mask before using in Laravel validator?

I have a form field to get mobile number of users:

<input class="form-control" name="mobile" data-mask="0999 999 9999" type="text" id="mobile" />

I used jasny input mask to guide users for entering data but I need to save mobile number in format 999999999 into database (Without 0 and spaces).

As I use ajax to send data to server by serialize() function, I don't want to use client side script to change entered value (I have many such form fields) unless by changing or adding a function or method to jasny input mask to use on all such fields!

I get the entered value server-side and I want to assign it to a model attribute in Laravel 5 so in user model I declared an accessor and a mutator to set and get mobile number:

public function setMobileAttribute($value){
    $value = substr(str_replace(" ","",$value),1);
    $this->attributes['mobile'] = $value;
}

and

public function getMobileAttribute($value){
    return '0'.substr($value,0,3).' '.substr($value,3,3).' '.substr($value,6,4);
}

It works nice but when I want to use Laravel validation to indicate it's a unique field, it doesn't work. Peace of code is like:

class UserController extends Controller {

    protected $rules = ['mobile' => 'required|unique:users'];
    public function store(Request $request){
        $validator = Validator::make($request->all(), $this->rules);
        if ($validator->fails()){
            return response()->json([
                'success' => false,
                'errors' => $validator->getMessageBag()->toArray()
            ]);
        }
        // codes to store user...
    }
}

It cause to error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

I found a way not perfect but is good. I add this function to my UserController class:

private function sanitize(Request $request){
    $input = $request->all();
    $input['mobile'] = substr(str_replace(" ","",$input['mobile']),1);
    $request->replace($input);
    return $request->all();
}

and use Laravel validator like this:

$validator = Validator::make($this->sanitize($request), $this->rules);

I was facing same issue so I have solved it, here is my code:

$mobile = str_replace(['(', ')', ' ', '-'], ['', '', '', ''], $request->post('mobile'));
$request->merge(array('mobile' => $mobile));

    $request->validate([
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'max:50', 'min:8'],
        'phone' => ['required', 'unique:users']
    ]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM