Coordinate verification
P粉982009874
P粉982009874 2023-07-28 09:27:27
0
1
511
<p>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). </p><p>This is the text field: </p><p><br /></p> <pre class="brush:html;toolbar:false;"><ValidationProvider v-slot="{ errors }" rules="coordinates_validation"> <v-text-field :label="$t('stations.position')" :value="positionValue" :error-messages="errors" @input="$emit('update:station', { ...station, ...getLatLong($event) })" @keypress="justNumber" /> </ValidationProvider> </pre> <p>Here are two things I tried without success: </p> <pre class="brush:js;toolbar:false;">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"), }); </pre> <pre class="brush:js;toolbar:false;">extend('coordinates_validation', { validate: (value) => { const regex = /^d (.d )?,s*d (.d )?$/; return regex.test(value); }, message: i18n.tc('validations.coordinates_incorrect_format'), }); </pre> <p>Does anyone know how to fix this? </p>
P粉982009874
P粉982009874

reply all(1)
P粉682987577

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:

Number.isFinite(parseFloat(coord))

Your initial value.split only works with commas ",". I recommend splitting on spaces, commas, and any number of spaces.

const coordinates = value.split(/[,\s]\s*/);

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template