jQuery Validation plugin in ASP.NET Web Forms - asp.net

I would really like use the jQuery Validation plugin in my ASP.NET Web Forms application (not MVC). I find it easier than adding asp validators everywhere and setting the control to validate field on all of them.
I am just having some issues both when setting the class like this class="required email" which I think has something to do with having a form tag within the main form tag.
I also run into issues when calling the jquery validate using the names which become mangled in an asp control
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
username: {
required: true,
minlength: 2
}, },
messages: {
username: {
required: "Please enter a username",
minlength: "username at least 2 characters"
},
}.
.......
<p>
<label for="username">
Username</label>
<input id="username" name="username" />
</p>
because this
<asp:TextBox ID="tbUsername" runat="server"></asp:TextBox>
renders as
<input name="ctl00$ContentPlaceHolder1$tbUsername" type="text" id="ctl00_ContentPlaceHolder1_tbUsername" />
and mangles the name. I can get the ClientID using <%=tbUsername.ClientID %>but that doesn't work with ClientName
Has anyone had any success using the jquery validator plugin with asp.net?
If so what about using multiple forms much like using separate validation groups?

You can checkout the rules add function, but basically here's what you can do:
jQuery(function() {
// You can specify some validation options here but not rules and messages
jQuery('form').validate();
// Add a custom class to your name mangled input and add rules like this
jQuery('.username').rules('add', {
required: true,
messages: {
required: 'Some custom message for the username required field'
}
});
});
<input name="ctl00$ContentPlaceHolder1$tbUsername" type="text" id="ctl00_ContentPlaceHolder1_tbUsername" class="username" />
This way no need to worry about the crappy identifiers generated by the webforms engine.

Here are examples of using the jQuery Validation plugin with WebForms and emulating the concept of validation groups with it. It actually works pretty well once you smooth out a couple issues.

$("#signupForm").validate({
rules: {
<%= tbUsername.UniqueID %>: {
required: true,
minlength: 2
}, },
messages: {
<%= tbUsername.UniqueID %>: {
required: "Please enter a username",
minlength: "username at least 2 characters"
},
});
<asp:TextBox ID="tbUsername" runat="server"></asp:TextBox>

You can check xVal.webForms here: http://xvalwebforms.codeplex.com/

Tested what Darin Dimitrov said and it works perfectly, but if you don't want to set a specific class to each of your fields, you can use jQuery selectors:
$('form').validate();
$('input[id$=Username]').rules('add', {
required: true,
messages: {
required: 'Some custom message for the username required field'
}
});
<input name="ctl00$ContentPlaceHolder1$tbUsername" type="text" id="ctl00_ContentPlaceHolder1_tbUsername" />

The best solution is use "<%=tbUsername.UniqueID %>" instead of tbUsername in jQuery rules.
$("#signupForm").validate({
rules: {
"<%=tbUsername.UniqueID %>": {
required: true,
minlength: 2
}, },
messages: {
"<%=tbUsername.UniqueID %>": {
required: "Please enter a username",
minlength: "username at least 2 characters"
},
}.

I recently posted a patch file for xVal.WebForms which resolves the multiple forms issue relaying on the well known ASP.Net validation Group. This patch also supports the ASP.Net CausesValidation property.
Yo can read about it here: http://cmendible.blogspot.com/

A great way to do this is to use:
<%= textbox.Name %> or <%= textbox.ClientId %> whenever you need to reference a server item.
i.e.
var phoneNumb = $('#<%= tPhone.ClientID %>').val();
or
$("#signupForm").validate({
rules: {
<%= username.Name %>: {
required: true,
minlength: 2
}, },
messages: {
<%= username.Name %>: {
required: "Please enter a username",
minlength: "username at least 2 characters"
},
}.
.......

For SharePoint 2010 I found with loading different usercontrols as views (via ajax) that this worked if you move javascript into a library and can't use server tags for the control id's like this:
e.g #<%= tPhone.ClientID %>
$('input[id$=tPhone]').rules('add',
{
required: true,
messages:
{
required: 'Some custom message for the username required field'
}
});
Further to this if you dynamically load a user control via Ajax then you cannot use $(document).ready
You will have to encapsulate the jQuery in a function library if its on the User Control at (server side event) page load its fine but in the scenario its loaded via Ajax with the Update Panel it will not dance.
I have not tried loading usercontrols via jQuery yet, this looks heavy and appears to load the whole page albeit perhaps slightly quicker or not.
Tests comparing loading techniques showed the Update Panel was as fast and resulted in the same or smaller page sizes than other techniques and basically loaded quicker or much more data as quick or quicker.

I recommend using jQuery.simple.validator, its easy, lightweigh and customizable validator compatible with asp.net web forms, because basically it can perform validations in any container, not only
https://github.com/v2msoft/jquery.simple.validator
I recommend you check the plugin and the documentation.
Usage:
<script type="text/javascript" src="/Content/js/jquery-plugins/jquery.simple.validator.js"></script>
<div id="container">
<!-- REQUIRED FIELD -->
<label>Required Field: </label><br/>
<input type="text" id="required_field_control" data-required data-required-msg="Field is required" /><br /><br/>
<input type="button" value="Validate" onclick='javascript:validate();' />
</div>
<script type="text/javascript">
function validate() {
$("#container").initialize();
var ok = $("#container").validate();
if (!ok) alert("There are errors");
else alert("Form is ok");
}
</script

The information in this article led me to use Control.ClientID when looking for a match with jQuery... Very useful information...
<label for="<%= tbName.ClientID %>">Name</label>
<input id="cphBody_tbName" runat="server" .../>

Related

vee-validate 4.7 | VueJS 3 | Single input field validate

I am using VueJS 3 and want to validate my step by step screen with single OR multiple input fields and want to check is he field valid or not and based on that I have to enable next button.
For validation I am using vee-validate plugin 4.7.3.
In my case I also do not want to use the form tag if possible. As my field is independent so no need to use form.
But as I search and read the comments of the package owner and mentioned that need to use Form so I used it but I just want to check the field validation as I have to show/hide the next button.
Component.vue
<template>
<Form :validateOnModelUpdate="true">
<Field name="mobile" as="input" :rules="mobileRules" v-model="mobile" />
</Form>
// Want to display button if the validation match
// Out side of the form
<button class="btn btn-default" v-if="IF_VALID" > Next </button>
</template>
<script>
import * as Yup from 'yup';
export default {
data(){
return {
mobile: '',
mobileRules: Yup.string().required().min(6)
}
}
}
</script>
If is there anyway to access the meta of the Field then may be that will be helped me.
Thanks.
I have tried to user UseField/useIsFieldValid but it shows me error that the
field with name mobile was not found
Also tried to use ref on the field but I can't able to access the meta of the Field
I have fixed it by using following code change:
For the field level validation need to code like this.
You can access field meta data in your component anywhere out of the Form
As per the owner comment if need to access this type of data out of the component need to achieve like this.
Owner Comment on Discussion
<template>
<div>
<form > <!-- This is simple HTML form -->
<input class="form-control" type="text" name="mobile" v-model="mobile" placeholder="000-0000-000">
<span class="text-danger" v-if="mobileErr">{{ mobileErr }}</span>
</form>
<button v-if="mobileMeta.valid"> Next </button>
</div>
</template>
<script>
import * as Yup from 'yup';
import { useField } from 'vee-validate';
export default {
setup(){
const mobileRules = Yup.string().required('Required').min(10, 'Must be 10 digits');
const { meta: mobileMeta, value: mobile, errorMessage: mobileErr} = useField('mobile', mobileRules);
return {
mobileMeta,
mobile,
mobileErr
}
},
data(){
return {
steps: '',
loading: false
}
},
created(){
},
methods:{
methodOne () {
// Some code to perform
},
methodTwo () {
// Some code to perform
}
}
}
</script>
Hopefully it will helps to others who want to perform step by step form and need to valid the field one by one.
Thanks.

how to change style error message for required field

How do I change the message style? Or can I delete messages?
To be able to put this message background color or font changes?
Looks like you are using the jQuery validate() plugin.
To change the message itself, you can do this through an attribute or through a function in your jQuery.
Attribute:
<form>
<input name="firstname" required data-msg="Enter your custom message here">
</form>
jQuery:
$("form").validate({
rules: {
firstname: "required"
},
messages: {
firstname: "Enter your custom message here"
}
});
I highly recommend taking notes from their "Remember the Milk" example form, which customizes everything about the error messages.
http://jqueryvalidation.org/files/demo/milk/

Not able to post form in Adode CQ5

I am a newbie in AdobeCQ5. I am facing some trouble in posting form. Here is my Structure -
/apps/<myproject>/components/mytestcomponent
mytestcomopnent.jsp has following code -
<form id="myForm" action="<%=resource.getPath()+".html" %>">
<input type="text" id="t1" class="input-small" placeholder="Temprature F" />
<input type="text" id="t2" class="input-small" placeholder="Temprature C" readonly/>
<button type="button" id="cbtn" class="btn">Convert</button>
</form>
<script>
$(document).ready(function() {
$('#cbtn').click(function () {
var URL = $("#myForm").attr("action");
alert(URL);
var t1=$("#t1").val();
var t2=$("#t2").val();
$.ajax({
url: URL,
data:{'t1':t1},
type:"post",
success: function(data, status) {
$("#t2").val(data);
},
error: function( xhr, txtStat, errThrown ) {
alert("ajax error! " + txtStat + ":::" + errThrown);
}
});
});
});
</script>
This is giving my response code 200 (Success) but the output is not desired. My mycomponent.POST.jsp has following code -
<%
// TODO add you code here
String t1=request.getParameter("t1");
%>
<%= t1 %>
It gives the following output
Content modified /content/imobile/en/jcr:content/social.html
Status
200
Message
OK
Location /content/imobile/en/_jcr_content/social.html
Parent Location /content/imobile/en/_jcr_content
Path
/content/imobile/en/jcr:content/social.html
Referer http://example.comt:4502/content/imobile/en.html
ChangeLog
<pre></pre>
Go Back
Modified Resource
Parent of Modified Resource
Please help to resolve this.
The JSP file handling the POST method for your component should be named POST.jsp rather than mycomponent.POST.jsp.
Please notice that if you intercept all POST requests to your component, you won't be able to edit it on the author instance using a dialog (as the dialog simply POSTs data to the component URL). To avoid it, consider using a custom selector (like form). Your form should look be declared like this:
<form id="myForm" action="${resource.path}.form.html">
and the script handling POST request should be called form.POST.jsp.
The second important thing is that you should use Java classes rather than JSP files to store business logic. In this case it means that the form.POST.jsp script can be replaced with a Sling servlet declared as follows:
#SlingServlet(
resourceTypes="myproject/components/mytestcomponent",
methods="POST",
selectors="form")

jQuery Validation Engine - Required Field using regular expression

I am using jQuery Validation Engine in asp.net form. How do I validate a field (required) using a regular expression?
http://www.position-relative.net/creation/formValidator/
jQuery(document).ready(function () {
// binds form submission and fields to the validation engine
jQuery("#aspnetForm").validationEngine('attach', {
'custom_error_messages': {
// Custom Error Messages for Validation Types
'.reqSomeField': {
'required': {
'message': "Please enter Some Field."
}
}
}
});
});
What have you tried thus far?
But here's something that might help you get started. It's from the docucmentation.
custom[regex_name]
Validates the element’s value to a predefined list of regular expressions.
So first you'd need to create your custom regex in the jquery-validation-engine.js file, then call it in the form field. The syntax, in the form field, would be something like this:
<input value="someone#nowhere.com" class="validate[required,custom[email]]" type="text" name="email" id="email" />
Have you tried simply adding this class to the form fields?
<input value="" class="validate[required]" type="text" name="email" id="email" />
That doesn't do any validation other than force the user to put SOMETHING in the field. However, they could enter $$$ into the field, and the form would see that as valid. If you're doing inline validation, and using this plugin in particular, you might want to use the existing validation options for email addresses, something that has letters and numbers but no punctuation, a numbers-only field, et cetera. The pre-existing options are all listed in the documentation.

JQuery validate dynamically add rules

I am currently using the validate plugin to validate a form (using ASP.Net controls). I have stripped out the rules from the standard setup within the form.validate method ie:
$("form").validate({
rules: {
ctl00$ContentPlaceHolder1$dgQuestions$ctl14$iRadList_Col0: "required"
}
});
I now have these in various functions which add the ruless depending on what button is clicked. This works fine for text boxes, but for a RadiobuttonList when the plugin tries to add the rule there is an error saying the element is undefined.
function addRuleSet() {
$("#ctl00$ContentPlaceHolder1$dgQuestions$ctl14$iRadList_Col0").rules("add", { required: true });
}
I think the problem is that I am using the name attribute (asp puts $ in )to define the group that the radio buttons belong to rather than an id (, but in the static settings all the elements are definied using the name attribute. Anyway I am not sure how to get around adding a rule for a group of associated radio buttons, any advice would be appreciated.
PS I really need to call the RadioButtonList rather than the individual radio buttons.
You can also apply a rule by setting classes on the element. For example, if you give the class "required" to an input, then the required rule applies to that element. To do this, you'd use the CssClass property on the control. You may need to experiment with compound controls, like RadioButtonList, to make sure that the class is being applied to the input elements generated, not the container. If you have trouble with this, one way to do it would be to add the class using jQuery after the page loads based on a selector.
<asp:RadioButtonList id="RadList" runat="server" CssClass="required">
...
</asp:RadioButtonList>
or
<script type="text/javascript">
$(function() {
$(':radio').addClass('required');
$('form').validate();
});
</script>
For a complex, class-based rule you can add new rules using addClassRules.
<script type="text/javascript">
$(function() {
$.validator.addClassRules({
range0to10: {
range: [0, 10]
},
name: {
minlength: 2,
required: true
}
});
$('form').validate();
});
</script>
<form ... >
<input type="text" name="rating" id="rating" class="range0to10" />
<input type="text" name="firstName" id="firstName" class="name" />
<input type="text" name="lastName" id="lastName" class="name" />
</form>
After days of this driving me mad, asking the question got me thinking how to get the element returning properly, and I came across this method of referencing staright away which allows me to do it:
$("input:radio[name='ctl00$ContentPlaceHolder1$dgQuestions$ctl14$iRadList_Col0']").rules("add", { required: true });

Resources