search

Home  >  Q&A  >  body text

Coordinate verification

<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粉982009874P粉982009874492 days ago514

reply all(1)I'll reply

  • P粉682987577

    P粉6829875772023-07-29 07:47:05

    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.

    reply
    0
  • Cancelreply