Quickly check that required fields have been filled out

Required Field Validation on VisualForce with Javascript

When writing a custom VisualForce page, you commonly need to verify that required fields have been filled out.

However, when you design complex pages with multiple ajax requests and dynamic rendering, using the required="true" parameter on tag elements becomes a problem. Using APEX to validate your input is also a much more cumbersome experience to your users as the data has to be sent to the server, validated, and returned - sometimes with nasty errors that you didn't think to handle. By throwing a little javascript into the equation, you can quickly and easily check that all required fields have been filled out - and even prevent your action method from running! But, enough talk.

Let's look at the code.

You see that the onclick event of the button calls out fieldsFilledOut() javascript function; the function returns true if all fields are filled out. If the function returns false (there is a missing field), the action method is not called because our onclick method will return false. A nice feature to add to your page is an instant check while the user is filling it out. If they tab to a field and then skip it, it's nice to instantly show them "Nope, you actually need to fill this one out". We use a function called checkVal() for that and pass in the "this" variable which resolves to the specific element calling the function:

**NOTE** For any field that you are using a selectlist (dropdown) option you should use the onchange action instead of onkeyup.**

You may be wondering about the styleClass="mustFillOut". This is to make it super easy to grab all the fields that should be required. As long as you do not have an actual css class called "mustFillOut" you can use this on any input element you want to require - even in cascade if you have other style classes applied to the element.

Here is the actual code for the two functions, checkVal() and fieldsFilledOut() that we have been talking about.

When calling the fieldsFilledOut() function, you'll notice we display an alert to the user notifying them that they need to fill out all the required fields.

That's it! You're done!

Check back soon for a follow up post on how to make the functions dynamic enough to allow for multiple "sections" of required fields depending on which button / action you are trying to call.

Leave a Comment
comments powered by Disqus

Support Options