colinaut / alpinejs-plugin-simple-validate

Simple Alpine form validation plugin
105 stars 5 forks source link

RegEx validation fails #4

Closed Rocketpilot closed 2 years ago

Rocketpilot commented 2 years ago

Possibly a bug, possibly user error:

I have a form input for a staff ID number, which has the form of the lower case letter "s" followed by any number of numerals.

A very simple regex based validation as follows works extremely well:

'x-validate': '/^Robert$/.test($el.value)'

But this more complex validation does not appear to:

'x-validate': '/^s(\d+)$/.test($el.value)'

Executing the test in the browser console (with an arbitrary but correctly formed id number instead of $el.value) returns TRUE.

colinaut commented 2 years ago

The above code for including an ad hoc test looks wrong. This is how you would add an ad hoc test like that:

<input type="text" id="staff-id-number" name="staff-id-number" x-validate="/^s(\d+)$/.test($el.value)" data-error-msg="proper staff id number required (s00000000)"/>

I tested it and it works for me. Basically the plugin takes the expression part in "" and evaluates it as a function. If it's === false than it is invalid. Anything else it defaults to valid.

Rocketpilot commented 2 years ago

Sorry, I cut the code straight from my Twig template - we're using Symfony's form builder for our forms so that's how you attach custom attributes to the HTML... it renders out the same way as you've shown.

I then took the code to the example folder in your plugin and made a cut-down page with just that input, and it works. So I think there must be some very annoying interaction with Webpack or something that's killing my attempts to implement here. Thank you for providing the example!

colinaut commented 2 years ago

Huh I wonder if webpack is killing Alpine evaluating expressions — so that the regex test isn't being run at all. That's my guess since the code that tests ad hoc tests is pretty simple and relies on Alpine included functions. Maybe you'll need to tweak your webpack config, but that's beyond may ability to help.

Rocketpilot commented 2 years ago

Yeah definitely more of a "me" problem here, haha.

But, in case this helps you down the track on a similar problem:

I replaced the \d with the explicit operator, like so /^s([0-9]+)$/ and it started working. About to slam my head into my desk. Computers, eh?

colinaut commented 2 years ago

I replaced the \d with the explicit operator, like so /^s([0-9]+)$/ and it started working. About to slam my head into my desk. Computers, eh?

Weird!?! I guess it's a strange interaction happening with regex and webpack and alpine? Glad you got it working!