MJRoz
MJRoz

Reputation: 73

How do I compare and verify user input field to stored data BEFORE to sending form in ColdFusion

I’m updating a site for my brother who teaches training courses. He has a registration form on the site that collects name, age, address, etc. That information is sent to him through cfmail with a copy sent to the registrant. The registrants then mails in a check via snail-mail to complete the registration. (My brother does NOT want to use an online payment method.)

Included in the form is the course name, location and fee. He asked if it was possible to implement some sort of “Promo Code” to offer discounts to select users. I’ve added PromoCode and PromoCode_Fee columns in SQL and am able to make it all work throughout the process.

My problem is on the user end. If the user mistypes the PromoCode in the form, the app will obviously not register the discount, send the registration emails out with the standard fee, and store the registration info in the DB. The only way for the user to fix the PromoCode would be to re-register, which would re-send the emails and add a new registration to the DB.

What I’d like to do is verify that the user entered a valid PromoCode in the input field PRIOR to submitting the form by comparing what they typed to the PromoCode stored in the DB. If the PromoCode doesn’t match, add “Promo Code is invalid” under the input field.

I do this as a hobby, am self-taught and am not sure if it’s even possible (or good idea.) I imagine it’s not possible to do with ColdFusion and would most likely need some sort of JS or jQuery - both of which I’m pretty illiterate in.

I’ve been searching for hours to see if anyone had any similar questions, but have come up short. Any help or pointing me in the right direction would be greatly appreciated.

Here's the code I'm putting together:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> 
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/scripts/jquery.validate.js"></script>

<script>
    $(document).ready(function() {
        var validator = $("#signupform").validate({
            rules: {
                firstname: "required",
                lastname: "required",
                username: {
                    required: true,
                    minlength: 2,
                    remote: "/components/promocodecomponent.cfc?method=validateUserName"
                }
            }
        });
    });
</script>


<div class="row justify-content-center">
    <div class="col-10">
        <form id="signupform" autocomplete="off" method="get" action="">
            <table>
                <tr>
                    <td class="label">
                        <label id="lfirstname" for="firstname">First Name</label>
                    </td>
                    <td class="field">
                        <input id="firstname" name="firstname" type="text" value="" maxlength="100">
                    </td>
                    <td class="status"></td>
                </tr>
                <tr>
                    <td class="label">
                        <label id="llastname" for="lastname">Last Name</label>
                    </td>
                    <td class="field">
                        <input id="lastname" name="lastname" type="text" value="" maxlength="100">
                    </td>
                    <td class="status"></td>
                </tr>
                <tr>
                    <td class="label">
                        <label id="lusername" for="username">Username</label>
                    </td>
                    <td class="field">
                        <input id="username" name="username" type="text" value="" maxlength="50">
                    </td>
                    <td class="status"></td>
                </tr>
                <tr>
                    <td class="field" colspan="2">
                        <input id="signupsubmit" name="signup" type="submit" value="Signup">
                    </td>
                </tr>
            </table>
        </form>
    </div>
</div>

Here's the component code:

component {
    remote boolean function validateUserName(string username) returnFormat="json"{
        
        if (arguments.username == "john") {
            return true;
        }

        return "Username already in use";
    }

}

Upvotes: 2

Views: 562

Answers (2)

SOS
SOS

Reputation: 6550

I do this as a hobby, am self-taught ... I imagine ... would most likely need some sort of JS or jQuery - both of which I’m pretty illiterate in.

The plugin is easy to use but there may be a slight learning curve depending on your jQuery and javascript skills. Bigger tasks are easier to tackle if you you break them into smaller ones and solve those one at a time. Start with the code snippet @AdrianJMoreno posted and delve into the documentation to understand what the code is doing and how:

  • validate() - a function that initializes the plugin for a specific form
  • rules - options that tells the plugin which form fields should be validated and how
  • remote - remote url to be called via ajax to validate a field's value. The remote endpoint should either return true/false or true/"some custom error message";

1. Build Sample Form

Once you have a sense of how the plugin works, move on to building a scaled down version of the Milk demo form using the code snippet.

JQuery and Validate libraries

   <!-- modify js paths as needed -->
   <script src="scripts/jquery-3.1.1.js"></script>
   <script src="scripts/jquery.validate.min.js"></script>

Javascript initialization (so plugin validates the form)

    <script>
    $(document).ready(function() {
        var validator = $("#signupform").validate({
            rules: {
                firstname: "required",
                lastname: "required",
                username: {
                    required: true,
                    minlength: 2,
                    remote: "users.action"
                }
            }
        });
    });
    </script>

  

HTML form (only the fields in code snippet)

    <form id="signupform" autocomplete="off" method="get" action="">
        <table>
            <tr>
                <td class="label">
                    <label id="lfirstname" for="firstname">First Name</label>
                </td>
                <td class="field">
                    <input id="firstname" name="firstname" type="text" value="" maxlength="100">
                </td>
                <td class="status"></td>
            </tr>
            <tr>
                <td class="label">
                    <label id="llastname" for="lastname">Last Name</label>
                </td>
                <td class="field">
                    <input id="lastname" name="lastname" type="text" value="" maxlength="100">
                </td>
                <td class="status"></td>
            </tr>
            <tr>
                <td class="label">
                    <label id="lusername" for="username">Username</label>
                </td>
                <td class="field">
                    <input id="username" name="username" type="text" value="" maxlength="50">
                </td>
                <td class="status"></td>
            </tr>
            <tr>
                <td class="label">
                    <label id="lsignupsubmit" for="signupsubmit">Signup</label>
                </td>
                <td class="field" colspan="2">
                    <input id="signupsubmit" name="signup" type="submit" value="Signup">
                </td>
            </tr>       
            </table>
    </form>

2. Test (Sample Form)

Test out the form in a browser. Since all fields are required, leaving the fields blank and submitting should trigger error messages on submit

Form With Errors

3. Create Remote URL

The live demo form uses a mocking library to simulate a remote ajax call. The mock url "users.action" must be replaced with a real url on your server. That url will point to a new component (or "CFC") you create. The component should contain a remote accessible method that validates a given username.

Keep things simple for the initial test. Have the method return true if the input equals a test value like "John" and false for everything else. Ultimately you'll replace that with real business logic, like a database lookup, but one step at a time.

YourComponentName.cfc

component {
    remote boolean function validateUserName(string username) returnFormat="json"{
        
        if (arguments.username == "john") {
            return true;
        }

        return false;
    }

}

4. Test (Remote URL)

To test a remote method in a browser, specify the path, name of the method to invoke, and any parameters that method expects. Verify the component returns the expected results. The result should be true for username=John and false for any other value.

Example url:

https://localhost/path/YourComponentName.cfc?method=validateUsername&username=john

Valid: UserName=John:

Test Remote URL with Valid Value

InValid: UserName=Bob:

Test Remote URL with Invalid Value

5. Fix Remote URL

With the component working, update the javascript code to point to the new cfc. Omit the username parameter because the plugin will pass it to the ajax call automatically.

For example, if the component location on disk is:

c:\path\webroot\path\YourComponentName.cfc 

Use the url:

/path/YourComponentName.cfc

JS Snippet:

...,
username: {
   ...,
   remote: "/path/YourComponentName.cfc?method=validateUserName"
}

6. Test Form (.. are you sensing a theme?)

Test the final form again with both a valid and invalid usernames to confirm it works as expected.

  • Invalid usernames "Mike" or "Bob" should trigger an error
    Invalid Username
  • Valid username "John" should not trigger an error Valid UserName

Next Steps ...

Continue to expand the working example and learn more about the plugin features by adding some customization. The next steps are left as an exercise for the reader ...

  • Replace hard coded test logic in the cfc with a database lookup
  • Replace default error message "Please fix this field" with a more user friendly message
  • Change the appearance of valid and invalid fields using CSS

Upvotes: 1

Adrian J. Moreno
Adrian J. Moreno

Reputation: 14859

Usually, you'd need to post some code that you've tried and isn't working. But you've outlined what you want and are just not sure where to start.

You can test just the value of the discount code before allowing the whole form to be submitted. You don't say how you're doing client-side form validation. I'd suggest using jQuery Validate to handle that, it's very easy to implement.

https://jqueryvalidation.org/documentation/

Go to the demo "The Remember The Milk sign-up form". This form checks the username field via Ajax before the rest of the form can be submitted.

var validator = $("#signupform").validate({
    rules: {
        firstname: "required",
        lastname: "required",
        username: {
            required: true,
            minlength: 2,
            remote: "users.action"
        }
    }
});

If not using this framework, then just make an Ajax request when change is triggered on the discount code field and make sure there's a positive response from that before you allow the form to be submitted.

Also, you need to do server-side validation of the discount code when someone submits the form. If they've entered a discount code that is invalid, then don't allow the form to be processed until they enter a valid code or they clear the value from that field.

Upvotes: 2

Related Questions