Html Custom Attribute creation and validation - javascript

I would like to create the validation for the controls dynamically. I have a page with more than 25 controls, those controls visibilities are based on the category and subcategories. For some of the categories the controls are required and some of them its not required. This is the business logic behind the scene.
So what I am planning here is, based on the categories and sub categories selection I am planning to include a html attribute isMandated=true for all the required fields. And on the onblur event going to validate its value. While clicking the button (while posting the page to server) I am planning to validate all the controls based on the isMandated attribute.
Is this approach is correct and all major browsers will support this kind of attribute addition?

If you want to include additional attributes you need to use the data- prefix. So in your case:
data-isMandated="true"
This is supported in all major browsers. To then grab the data using something like jQuery:
var isMandated = $(selector).attr("data-isMandated");

If you work on asp.net you can use the RequiredFieldValidator on your different control such as the following example :
<tr>
<td>
<asp:RequiredFieldValidator runat=server
ControlToValidate=txtName
ErrorMessage="Identifier is required."> *
</asp:RequiredFieldValidator>
</td>
<td>User Identifier :</td>
<td><input type=text runat=server id=txtName></td>
</tr>
For the required fields you can use ValidationSummary property which display an " * " before required fields.
<asp:ValidationSummary runat=server
headerText="there is error on this page/>
and don't forget the validation method :
public sub OnSubmit(source as Object, e as EventArgs)
if Page.IsValid then
' Some code
end if
end sub

Your page maybe will not be valid with HTML validations, if your attribute is "isMandated". The proper way is to create a custom attribute "data-isMandated". This approach will works on all browsers (I created similar page before and it was work on IE7+, FF, Chrome).
Maybe will be better, to add class to all required fields, instead of attribute isMandated=true and check all fields with this class.
Also, you can use jquery validation - plugin. It include a couple of validations rules, like required fields, min/max values, phone number validation, email validation, etc.

Related

Get Input Field value using DTM on Submitting a form

I have two input fields that had the user access card and password. and the user click on submit button to authenticate.
I'm using DTM in my app to capture the user navigation but I want also to get the values of those field to my DTM so I would know who the user is.
And here is what I tried but with no luck.
Created Data element as below:
And created Event based rule. But not sure how to get the values to be shown in my report:
Thanks for your help.
Example Form
Since you did not post what your form code looks like, here is a simple form based on what I see in the screenshots you posted, that I will use in my examples below.
<form id='someForm'>
User Name <input type='text' name='userName'><br>
Password <input type='password' name='userPass'><br>
<input type='submit' value='submit' />
</form>
Data Elements
Okay first, let's go over what you did wrong.
1) You said you want to capture two form fields, but you only have one data element...maybe? You didn't really convey this in your question. I just assumed as much because of what you did throughout the rest of the screenshots. But to be clear: you should have two separate data elements, one for each field.
2) The CSS Selector Chain value you used is just input, so it will select the first input field on the page, which may or may not coincide with one of the input fields you are looking to capture. So, you need to use a CSS selector that is unique to the input field you want to capture. Something as simple as input[name="userName"] will probably be good enough (but I cannot confirm this without seeing your site). You will need to do the same for the 2nd Data Element you create for the other input field (e.g. input[name="userPass"])
3) In the Get the value of dropdown, you chose "name". This means that if you have for example <input type='text' name='foo'>, it will return "foo". Since you want to capture the value the user inputs, you should select "value" from the dropdown.
Solution
Putting all the above together, you should have two Data Elements that look something like this (one for the user name field and one for the password field; only one shown below):
Event Base Rule
Okay first, let's go over what you did wrong.
1) The value you specified in Element Tag or Selector is input. You aren't submitting an input field; you are submitting a form. Input fields don't even have a submit event handler! Your Event Type is "submit", so at a minimum, Element Tag or Selector should be form. But really..
2) Ideally, you should use a CSS Selector that more directly and uniquely targets the form you want to trigger the rule for. For example, maybe the form has an id attribute you can target in your CSS Selector. Or maybe the form is on a specific page, so you can add additional conditions based on the URL. What combination of CSS Selector or other conditions you use to uniquely identify your form depends on how your site is setup. In my example form above, I added an id attribute, so I can use form#someForm as the CSS Selector.
3) You checked the Manually assign properties & attributes checkbox, and then added two Property = Value items. This tells DTM to only trigger the rule if the input has a name attribute with value of "userName" AND if it has a name attribute value of "userPass". Well name can't have two values at the same time, now can it!
<input name='foo' name='bar'> <!-- bad! -->
All of this needs to be removed, because again (from #1), you should be targeting a form, not an input field.
4) For good measure, looks like you added a Rule Condition of type Data > Custom, but the code box is empty. The rule will only trigger if the box returns a truthy value. Since there is no code in the box, it will return undefined (default value returned by a javascript function if nothing is returned), which is a falsey value. This also needs to be removed.
Solution
Putting all the above together, the Conditions section of the Event Based Rule should look something like this:
But again, ideally your conditions should be more complex, to more uniquely target your form.
Referencing the Data Elements
Lastly, you can reference the input fields to populate whatever fields in the various Tool sections with the %data_element% syntax. For example, you can populate a couple of Adobe Analytics eVars like this (data element names reflect the examples I created above):
Or, you can reference them with javascript syntax in a custom code box as e.g. _satellite.getVar('form_userName');
Additional Notes
1) I Strongly recommend you do not capture / track this type of info. Firstly, based on context clues in your post, it looks like this may count as Personally Identifiable Information (PII), which is protected under a number of laws, varying from country to country. Secondly, in general, it is a big security risk to capture this information and send it to Adobe (or anywhere else, really). Overall, capturing this sort of data is practically begging for fines, lawsuits, etc.
2) Note that (assuming all conditions met), the "submit" Event Type will track when the user clicks the submit button, which is not necessarily the same thing as the user successfully completing the form (filling out all the form fields with valid input, etc.). I don't know the full context/motive of your requirements, but in general, most people aim to only capture an event / data on successful form completion (and sometimes separately track form errors).

Check if field is required?

I need to find all required fields in given form using jquery. I was using this syntax:
$('input[required],select[required]')
This was doing job, but now I started using jQuery Validation Plugin. As i understood plugin would not add 'required' attribute to field, and thats why above script is failing to find required fields. Is it possible select required field when using jQuery Validation Plugin?
As I understood plugin would not add 'required' attribute to field, and thats why above script is failing to find required fields.
The jQuery Validate plugin does not dynamically add or remove attributes from the input elements. It only adds/removes a class depending on whether the field is valid or invalid.
Is it possible select required field when using jQuery Validation Plugin?
Not directly. There is nothing unique about an input when the field has the "required" rule declared by the plugin's settings.
However, with this plugin, rules can be declared on the fields using several other methods... just two examples follow.
Instead of declaring the required rule via the rules object within .validate(), simply add the HTML5 required attribute to the fields yourself. The jQuery Validate plugin will work by picking up this HTML5 attribute and assigning the required rule to the field for validation.
<input type="text" name="foo" required />
OR
<input type="text" name="foo" required="required" />
and you don't need to specify the element itself in the selector, just the attribute, like this...
$('[required]')
OR
$('[required="required"]')
You can also assign the rule via a class...
<input type="text" name="bar" class="required" />
then you can easily select all elements with this class...
$('.required')
This demo shows three different ways to assign the required rule.
DEMO: jsfiddle.net/fg25jsw3/

How to disable fields within a Javascript form

What is the best way of disabling(greying out) fields within a Javascript form? I have tried the disabled="disabled" on both the form and its fields but neither work e.g.:
<form:form id="testForm" method="post" disabled="disabled" action="${pageContext.request.contextPath}/testSave" commandName="testForm">
<tr>
<td valign="top" disabled="disabled">Name: </td>
<td valign="top"><form:input disabled="disabled" path="fName"/></td>
</tr>
</form:form>
Any ideas on what im doing wrong here?
Using JQuery you could do the following to disable all form fields for a given form:
$('#formId').find('input,select,textarea[,other elements]').prop('disabled', true);
Well, it sort of depends on exactly what you are trying to do.
The "sure fire" way of disabling form fields is a combination of "disabled" and "readonly" on the inputs. Between the two, you can cover everything that you could want:
grey out the input
make the input non-editable
make the input non-focasable
keep the input from being sent with the form
Since some browsers don't support the "greyed out" part of disabling, the best way to cover that is to set up a custom CSS to display disabled (or readonly) fields the way that you want them to show.
To get the right soluiton for what you want to do with your form, look here for the differences between the two attributes: http://kreotekdev.wordpress.com/2007/11/08/disabled-vs-readonly-form-fields/
Edit: Additionally, you might consider replacing the disabled inputs with text, if the data is not to be sent with the form . . . less confusing to the user than having an input field that they can't use.
See the below js sample; I hope my perception matches with your wish:
http://jsbin.com/avopuf/3/
Change css as per your requirement.
You can disable input tags, but not td
td tag attributes
Sounds like you can use a reference site to brush up on HTML. I find W3School to be a good starting point, it has tutorials and references for a variety of online technologies.
Specifically for HTML and HTML input tag
Also, how is it not working? (Is it not greying out, or user can still type in it, ...?)

HTML5 Browser Validation - 1 form, 2 buttons, need to change validation

I have a form with two buttons - one is a "submit" button at the end of the form, and in the middle of the form I have an "Add" button that uses Javascript to add hidden input elements within the form whenever it's clicked.
Here are the two input fields/add button:
<input name="name" required>
<input name="email" required type="email">
<button type="submit">Add</button>
And then another set of input fields:
<input name="title" required>
<button type="submit">Submit</button>
And these are all within one form.
I want HTML5 browser validation to fire on the "name" and "email" fields when I click "Add" (but not the "title" field) and the browser validation to fire on the "title" field (but not the "name" and "input" fields) when I click "Submit." Is there any way to accomplish this?
You can add or remove attribute "required" to the fields to which you required by
$('#field_id').attr('required','true');
$('#field_id').removeAttr('required');
Is there any particular reason that you want to use HTML5 to validate your form in the first place? I feel like what you need would be easily accomplished using Javascript, and you noted that your add button would be using javascript anyway. Also, why would your form validation to be partitioned in such an odd way?
I don't even like the HTML5 validation in the first place. For example, if you type in "asdf#1" into an HTML5 email input, it will accept it. Now, you can make the argument that that's technically a valid email address, but I think in practice most people would agree that they wouldn't accept that as a valid email address. You could use an IP address in place of the domain but I highly doubt that you could use that as an email to log into any modern web page.
But I digress. To answer your question, you could write a quick function with JQuery that would override the form validation based on which button was clicked. You would do this by catching the "invalid" error thrown by the HTML5 validation for that particular input and returning false to get around it. Therefore, when you clicked submit you could override the name and email form validation, and vice versa for when you click the add button. Again, I have no idea why you would want to do this but it is a solution.
The only way I see is to set the required attributes (or: properties) dynamically on-click.
Or you can add and remove event listeners for invalid, which seem to suppress the native "missing"/"wrong format" notice - even if they do nothing (like preventDefaultAction or so).
I also tried buttons with the formnovalidate attribute and manually checkValidity() on the elected elements, but even though that fires "invalid"-events no native dialogue is shown and the submit is not cancelled. (tested everything with opera)

Required Field Validator incorrectly failing validation on disabled textbox

A required field validator seems to always to fire when the associated textbox is disabled (whether the textbox contains text or not).
When the textbox is enabled the validator behaves correctly.
Can anybody tell me why?
I've tried disabling the required field validator with ValidatorEnable but that seems to make no difference.
Here's the relevant HTML from the page (cut down):
<tr id="trBrokerNetID" runat="server">
<td>
<cc1:mitextbox id="txtBrokerNetID" runat="server" cssclass="bodytext" width="220px" maxlength="20" onBlur="JavaScript:CheckBrokerBranch(false);"></cc1:mitextbox>
<asp:requiredfieldvalidator id="rfvBrokerNetID" runat="server" width="1px" errormessage="BrokerNetID - Please supply a value" controltovalidate="txtBrokerNetID">*</asp:requiredfieldvalidator>
</td>
</tr>
Any ideas gratefully received.
Now what I didn't know was that when a control is disabled on the clientside it doesn't get included in the postback.
Which is why the serverside validation was firing. As far as it was concerned the control was empty.
The soolution is to use the readOnly property rather than the disabled property.
Now to figure out how to style the control to make it have the same look as if it was disabled.
ASP.NET's validators work in mysterious ways :D
First of all it is dangerous to use the id of an ASP.NET control to access it in jQuery.
If you place the control in a repeater or wrap the page in a master page, then the id of the html element will be something different than the id you specified. Use class to access the element instead.
If ASP.NET validators want the field to be enabled then you must try another approach.
My suggestion would be this:
1.
Add a class to the textbox, that makes it looks disabled:
$("#txtBrokerNetID").addClass("thisClassMakesItLookDisabled");
2.
Add an event that checks on focus to the textbox and blurs it if there is focus:
$("#txtBrokerNetID").focus(function() {
$(this).blur();
});
Now the field behaves as if it is disabled and the validator works.
One option you can choose, is to set a ValidationGroup than the one the form uses, an then, when validating the form call Page_ClientValidate('text_validation_group') if needed. That way client validation won't get in the way.

Categories