I have a form with two text inputs that must be floats (specifically, these text inputs are for geographic coordinates
), looked at the documentation and found a rule for integer
and numeric
but not for float
.
I was thinking using the "numeric" because the text inputs are disabled and the value only changes when a marker on a map is moved.
What would be the best way to validate a float?
It validates the incoming data. By default, base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP requests with a variety of powerful validation rules.
Each form request generated by Laravel has two methods: authorize and rules .
You should add all your validation logic in the passes() function. It should return true or false based on the logic you have written in the function. The message() function returns a string that specifies the error message to be displayed in case the validation fails.
Custom Validation Rule Using Closures $validator = Validator::make($request->post(),[ 'birth_year'=>[ 'required', function($attribute, $value, $fail){ if($value >= 1990 && $value <= date('Y')){ $fail("The :attribute must be between 1990 to ". date('Y').". "); } } ] ]);
You may use a regular expression rule (regex:pattern
) for this and since you want to use to validate Geographic Coordinates
then you should use a regular expression rule because a Geo Coord
may look something like 23.710085, 90.406966
, which is the coordinates (lat long) of Dhaka Bangladesh
and it also may contain a coordinates like -33.805789,151.002060
. So here is the syntax:
$rules = array('form_field_name' => 'required|regex:pattern' );
Or maybe just
$rules = array('form_field_name' => 'regex:pattern' );
So, the pattern should be something like this /^[+-]?\d+\.\d+, ?[+-]?\d+\.\d+$/
. So, finally, it should look something like this (pattern is copied from internet
):
$rules = array('form_field_name' => 'regex:/^[+-]?\d+\.\d+, ?[+-]?\d+\.\d+$/');
Check the Laravel Validation (regex).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With