Coordinate verification
P粉982009874
P粉982009874 2023-07-28 09:27:27
0
1
452

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?

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
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!