I have a text field for coordinates and I want to validate it using vee-validate (3.x) and Vue 2. I tried two different methods with no success. The format of the coordinates should be "integer or float, integer or float", i.e. "latitude, longitude" (only one comma, multiple commas should be marked as invalid).
This is the text field:
Here are two things I tried without success:
extend("coordinates_validation", { validate: (value) => { const coordinates = value.split(","); if (coordinates.length !== 2) { return false; } const trimmedCoordinates = coordinates.map((coord) => coord.trim()); const isValidCoordinate = (coord) => { return !Number.isNaN(parseFloat(coord)) && Number.isFinite(coord); }; return ( trimmedCoordinates.every(isValidCoordinate) && !trimmedCoordinates.some((coord) => coord === "") ); }, message: i18n.tc("validations.coordinates_incorrect_format"), });
extend('coordinates_validation', { validate: (value) => { const regex = /^d (.d )?,s*d (.d )?$/; return regex.test(value); }, message: i18n.tc('validations.coordinates_incorrect_format'), });
Does anyone know how to fix this?
When you are not sure, you can view the output through console.log.
Please check my codesandbox. I use console.log to output step by step during the verification process, and split large steps into small steps when necessary.
For your first attempt, the problem is that Number.isFinite always returns false. This is because you passed it a string coord, but Number.isFinite expected a number. Here’s how to fix it:
Your initial value.split only works with commas ",". I recommend splitting on spaces, commas, and any number of spaces.
For your second attempt, just using regular expressions, I don't see any problems. When I put the code in the same codesandbox and use it as validation method it works perfectly.