Form validation. Optimize Angular ng-required expression - javascript

I'm creating a form validation and it becomes too ugly and heavy because of too many fields that need to be validated. I need to optimize it. So, I'm making required any field based on the other fields values using ng-required. When the user insert a value in one of the fields then the rest of them loose the required quality and the form becomes valid. So, for that I created an expression like this:
<input ng-model="field.one" ng-required="
!field.two &&
!field.three &&
!field.four &&
!field.five &&
!field.six &&
... &&
!filed.twenty"/>
<input ng-model="field.two" ng-required="
!field.one &&
!field.three &&
!field.four &&
!field.five &&
!field.six &&
... &&
!filed.twenty"/>
So, I intend to move the required expression in the controller or where you think it should be moved in order to optimize and organize the code. I was thinking to encapsulate it in a function inside of controller but I didn't succeed. I tried something like this:
VIEW
<input ng-model="field.one" ng-required="myFunc(field.one)"/>
CTRL
$scope.myFunc = function(modelField){
anything I tried in this fn I didn't make it to work syncronized with
the field models, updating their models based on user interaction :)
}
Please, is there someone that has an ideea how should be done? Thanks.

I would prefer one scope variable which is bound to all input field's ng-required attribute. And on change of any of the input field toggle this variable.
http://plnkr.co/edit/PVXVD9RKM8cMwCVjFA7c?p=preview
<input type="text" ng-change="onChange(userName1, 'name1')" name="name1" ng-model="userName1" ng-required="required">
<input type="text" ng-change="onChange(userName2, 'name2')" name="name2" ng-model="userName2" ng-required="required">
$scope.required = true;
$scope.userNames = [];
$scope.onChange = function(val, name) {
if (val) {
if ($scope.userNames.indexOf(name) == -1) {
$scope.userNames.push(name);
}
$scope.required = false;
} else {
if ($scope.userNames.indexOf(name) !== -1) {
$scope.userNames.splice($scope.userNames.indexOf(name), 1);
}
if ($scope.userNames.length === 0) {
$scope.required = true;
}
}
}

Related

Condition is Not checking properly in ng-if with !state.include

<select class="form-control"
ng-if="((!$state.includes('home.allprojects') ||
!$state.includes('home.Sentprojects')) &&
!dynamicFields.isShowVismaButtons)"
ng-model="projects.selectedBokYear" ng-change="onBokYearChange()"
ng-options="font.value for font in projects.bokYears"></select>
Here the code must display if the state is not in the home.allprojects or home.Sentprojects and !dynamicFields.isShowVismaButtons
ng-if="((!$state.includes('home.allprojects') || !$state.includes('home.Sentprojects')) && !dynamicFields.isShowVismaButtons)"
but the Select is visible even in the home.allprojects and home.Sentprojects state
can any one give a solution for it
You cant access $state in html,
Instead write a function which defines your logic and call that function from your HTML, or you can take a variable and use it in html for state
I prefer going with a function which I added in my answer.
HTML:
<select class="form-control"
ng-if="checkState()"
ng-model="projects.selectedBokYear" ng-change="onBokYearChange()"
ng-options="font.value for font in projects.bokYears"></select>
In controller,
$scope.checkState = function(){
return ($state.includes('home.allprojects')) ||
(!$state.includes('home.Sentprojects')) &&
(!$scope.dynamicFields.isShowVismaButtons)
}
I have created a checkState function from HTML and defined your logic there.
Also, to check the state directly if there is no parent-child, you can use $state.current.name
$scope.checkState = function(){
return ($state.current.name != 'home.allprojects') ||
($state.current.name != 'home.Sentprojects') &&
(!$scope.dynamicFields.isShowVismaButtons)
}

What is the value of an empty text input box?

I am trying to implement a search box. The following is the code (both HTML and JS)
HTML
<form>
<input type="text" ng-model="searchVar" class="searchbox">
<input type="button" value="Search" ng-click="Search()" class="button">
</form>
JS
var Search = function() {
/* code to implement the table content loading part */
//The following is what I have to filter out the table contents based on input in the text field
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {
ItemsToDisplay.push(tableContent[i])
}
//Call function to load table
}
What is happening is that, if I enter some string into the input text field, the search algorithm works fine and only the relevant items are displayed. However, if I clear the contents of the search box and click on Search button, nothing is displayed in the table. That is, when the text field is cleared and clicked on the search button, it is as if ItemsToDisplay is empty and the if condition fails.
Can someone explain why this is the case? And how I can solve this?
Before your indexOf($searchVar) you should check that searchVar is != ''. Otherwise no item will be displayed afterward. A suggestion, javascript has a really great console.log functionality that will help you a lot when it comes to if branches
If you cleared input, the value of $scope.searchVar willbe undefined and your condition
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {...}
will be false, so you didn't push into ItemsToDisplay and nothing append.
I suggest you to write an else statement :
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {...}
else {
ItemsToDisplay.push(tableContent[i]);
}
U can try with,
if (($scope.searchVar) != undefined)
or
if (typeof ($scope.searchVar) != 'undefined')
when you do not enter anything in INPUT box then its value become UNDEFINED.
you will have to check in if() condition, if input is undefined then write your logic, if input has some value then write your logic.
<form>
<input type="text" ng-model="searchVar" class="searchbox">
<input type="button" value="Search" ng-click="Search()" class="button">
</form>
var Search = function()
{
if ( $scope.searchVar == undefined){
//Do something, input box is undefined
}
if (($scope.searchVar) && (tableContent[i].indexOf($scope.searchVar) !== -1)) {
ItemsToDisplay.push(tableContent[i]);
}
}

Form validation - Required one of many in a group

In the project I'm working on at the moment I currently have three textboxes and I need to validate that at least one of the text boxes has been populated.
I've been reading into custom validation with Angular directives and I understand you can set the validity of an input in a directive's link function using the following:
ctrl.$parsers.unshift(function(viewValue) {
// validation logic here
});
The problem I have is that I don't need to set an individual input's validity.. I need to invalidate the entire form if the criteria isn't met. I just wonder how to approach this?
I'm thinking maybe I should create a directive that's placed on the enclosing form itself and then make the form invalid?
I suppose I'm just looking for some guidance into how I should go about this because I'm a little unclear where to start - all the material I'm reading on custom validation seems to be for when you're validating a specific input as opposed to a set of conditions on a form.
I hope I've made myself clear! Thanks..
You can use ng-required to force the user to fill at least one field by checkingthe length attribute of the string.
You can do the following for example:
<form name="myForm">
<input type="text" ng-model="fields.one" name="firstField" ng-required="!(fields.one.length || fields.two.length || fields.three.length)" />
<br/>
<input type="text" name="secondField" ng-required="!(fields.one.length || fields.two.length || fields.three.length)" ng-model="fields.two" />
<br/>
<input type="text" ng-model="fields.three" name="thirdField" ng-required="!(fields.one.length || fields.two.length || fields.three.length)" />
<br/>
<button type="submit" ng-disabled="!myForm.$valid">Submit</button>
</form>
See this working fiddle example for more details.
You can have more details about required vs ng-required by reading this question
There are several approaches and the best option depends on your exact requirements.
Here is one approach that I found to be generic enough and flexible.
By "generic" I mean it doesn't only work for text-fields, but also for other kinds of inputs, such as check-boxes.
It's "flexible" because it allows any number of control-groups, such that at least one control of each group must be non-empty. Additionally, there is no "spacial" constraint - the controls of each group can be anywhere inside the DOM (if required, it is easy to constrain them inside a single form).
The approach is based on defining a custom directive (requiredAny), similar to ngRequired, but taking into account the other controls in the same group. Once defined, the directive can be used like this:
<form name="myForm" ...>
<input name="inp1" ng-model="..." required-any="group1" />
<input name="inp2" ng-model="..." required-any="group1" />
<input name="inp3" ng-model="..." required-any="group1" />
<input name="inp4" ng-model="..." required-any="group2" />
<input name="inp5" ng-model="..." required-any="group2" />
</form>
In the above example, at least one of [inp1, inp2, inp3] must be non-empty, because they belong to group1.
The same holds for [inp4, inp5], which belong to group2.
The directive looks like this:
app.directive('requiredAny', function () {
// Map for holding the state of each group.
var groups = {};
// Helper function: Determines if at least one control
// in the group is non-empty.
function determineIfRequired(groupName) {
var group = groups[groupName];
if (!group) return false;
var keys = Object.keys(group);
return keys.every(function (key) {
return (key === 'isRequired') || !group[key];
});
}
return {
restrict: 'A',
require: '?ngModel',
scope: {}, // An isolate scope is used for easier/cleaner
// $watching and cleanup (on destruction).
link: function postLink(scope, elem, attrs, modelCtrl) {
// If there is no `ngModel` or no groupName has been specified,
// then there is nothing we can do.
if (!modelCtrl || !attrs.requiredAny) return;
// Get a hold on the group's state object.
// (If it doesn't exist, initialize it first.)
var groupName = attrs.requiredAny;
if (groups[groupName] === undefined) {
groups[groupName] = {isRequired: true};
}
var group = scope.group = groups[groupName];
// Clean up when the element is removed.
scope.$on('$destroy', function () {
delete(group[scope.$id]);
if (Object.keys(group).length <= 1) {
delete(groups[groupName]);
}
});
// Update the validity state for the 'required' error-key
// based on the group's status.
function updateValidity() {
if (group.isRequired) {
modelCtrl.$setValidity('required', false);
} else {
modelCtrl.$setValidity('required', true);
}
}
// Update the group's state and this control's validity.
function validate(value) {
group[scope.$id] = !modelCtrl.$isEmpty(value);
group.isRequired = determineIfRequired(groupName);
updateValidity();
return group.isRequired ? undefined : value;
}
// Make sure re-validation takes place whenever:
// either the control's value changes
// or the group's `isRequired` property changes
modelCtrl.$formatters.push(validate);
modelCtrl.$parsers.unshift(validate);
scope.$watch('group.isRequired', updateValidity);
}
};
});
This might not be so short, but once included into a module, it is very easy to integrate into your forms.
See, also, this (not so) short demo.
It's too late but might be can save some one's time:
If there are only two fields, and want to make one of them required then
<input type="text"
ng-model="fields.one"
ng-required="!fields.two" />
<br/>
<input type="text"
ng-model="fields.two"
ng-required="!fields.one" />
If you have three like in question then
<input type="text"
ng-model="fields.one"
ng-required="!(fields.two || fields.three)" />
<br/>
<input type="text"
ng-model="fields.two"
ng-required="!(fields.one || fields.three)" />
<br/>
<input type="text"
ng-model="fields.three"
ng-required="!(fields.one|| fields.two)" />
If more than this, I will suggest to write a function on scope and watch it.
See the working example
modification to ExpertSystem's answer (https://stackoverflow.com/a/24230876/4968547) so that his code works in the latest angularjs.
i changed the updateValidity() to set parse also to true/false
function updateValidity() {
if (group.isRequired) {
modelCtrl.$setValidity('required', false);
modelCtrl.$setValidity('parse', false);
} else {
modelCtrl.$setValidity('required', true);
modelCtrl.$setValidity('parse', true);
}
}
now its working fine for me
Ran into this same problem last week; ExpertSystem's solution was a good start, but I was looking for a few enhancements to it:
Use Angular 1.4.3
Use ngMessages
I eventually wound up with this example on JSFiddle - hope that helps inspire others in the same boat! Relevant JS code from the Fiddle:
var app = angular.module('myApp', ['ngMessages']);
app.controller('myCtrl', function ($scope) {
$scope.sendMessage = function () {
$scope.myForm.$submitted = true;
if ($scope.myForm.$valid) {
alert('Message sent !');
}
};
});
app.directive('requiredAny', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function postLink(scope, elem, attrs, ctrl) {
// If there is no 'ngModel' or no groupName has been specified,
// then there is nothing we can do
if (!ctrl || !attrs.requiredAny) { return };
// If this is the first time we've used this directive in this scope,
// create a section for it's data. If you need / want to make use of
// an isolate scope you'll need to make 'var groups' scoped to the directive;
// but then you may want to look in to clearing out group entries yourself
if (!scope.__requiredAnyGroups) {
scope.__requiredAnyGroups = {}
}
var groups = scope.__requiredAnyGroups;
// Create a bucket for this group if one does not yet exist
if (!groups[attrs.requiredAny]) {
groups[attrs.requiredAny] = {};
}
var group = groups[attrs.requiredAny];
// Create the entry for this control
group[attrs.ngModel] = {
ctrl: ctrl,
hasValue: false
};
ctrl.$validators.requiredAny = function(view, value) {
var thisCtrl = group[attrs.ngModel],
ctrlValue = (typeof value !== 'undefined') && value,
oneHasValue = false;
thisCtrl.hasValue = ctrlValue;
// First determine if any field in the group has a value
for (var prop in group) {
if (group.hasOwnProperty(prop) && group[prop].hasValue) {
oneHasValue = true;
break;
}
}
// Set the validity of all other fields based on whether the group has a value
for (var prop in group) {
if (group.hasOwnProperty(prop) && thisCtrl != group[prop]) {
group[prop].ctrl.$setValidity('requiredAny', oneHasValue);
}
}
// Return the validity of this field
return oneHasValue;
};
}
};
});
Here is a refactored take on ExpertSystems great post. I didn't need the destroy method so I gutted it.
I also added a grayed out explanation that may help in your code. I use this directive for ALL my required fields. Meaning when I use this directive I no longer use ng-required, or required.
If you want a field required just pass in a unique group name. If you don't want the field required then pass in null, and if you want to have many different groups just pass in a matching group name.
I believe there is a little more refactoring that could be done here. Angularjs states that when using $setValidity, that instead you should use $validators pipeline instead, but I could not get that to work. I am still learning this complex animal. If you have more info, post it!
app.directive('rsPartiallyRequired', function () {
var allinputGroups = {};
return {
restrict: 'A',
require: '?ngModel',
scope: { },
link: function(scope, elem, attrs, ctrl) {
if( !ctrl || !attrs.rsPartiallyRequired ){ return } // no ngModel, or rsPartialRequired is null? then return.
// Initilaize the following on load
ctrl.$formatters.push( validateInputGroup ); // From model to view.
ctrl.$parsers.unshift( validateInputGroup ); // From view to model.
if ( ! allinputGroups.hasOwnProperty( attrs.rsPartiallyRequired )){ // Create key only once and do not overwrite it.
allinputGroups[ attrs.rsPartiallyRequired ] = { isRequired: true } // Set new group name value to { isRequired: true }.
}
scope.inputGroup = allinputGroups[ attrs.rsPartiallyRequired ] // Pass { isRequired: true } to form scope.
function validateInputGroup(value) {
scope.inputGroup[ scope.$id ] = !ctrl.$isEmpty( value ); // Add to inputGroup ex: { isRequired: true, 01E: false }.
scope.inputGroup.isRequired = setRequired( attrs.rsPartiallyRequired ); // Set to true or false.
updateValidity(); // Update all needed inputs based on new user input.
return scope.inputGroup.isRequired ? undefined : value
}
function setRequired(groupName) {
if( ! allinputGroups[ groupName ] ){ return false } // No group name then set required to false.
return Object.keys( allinputGroups[ groupName ] ).every( function( key ) { // Key is 'isRequired' or input identifier.
return ( key === 'isRequired' ) || ! allinputGroups[ groupName ][ key ]
});
}
scope.$watch('scope.inputGroup.isRequired', updateValidity); // Watch changes to inputGroup and update as needed.
function updateValidity() { // Update input state validity when called.
ctrl.$setValidity('required', scope.inputGroup.isRequired ? false : true );
}
}
}
});
// This directive sets input required fields for groups or individual inputs. If an object in the template is given
// to the directive like this:
// Object: { "name": "account_number", "attrs": { "required": { "group": "two" }}}.
// HTML: <input type="text" rs-partially-required="{{ field.attrs.required.group }}" />
// Or anything where the evaluation is a string, for example we could use "groupOne" like this...
// HTML: <input type="text" rs-partially-required="groupOne" />
// Then this directive will set that group to required, even if it's the only member of group.
// If you don't want the field to be required, simply give the directive a null value, like this...
// HTML: <input type="text" rs-partially-required="null" />
// However, when you want to use this directive say in an ngRepeat, then just give it a dynamic string for each input
// and link the inputs together by giving the exact matching string to each group that needs at least one field. ex:
// <input type="text" rs-partially-required="null" />
// <input type="text" rs-partially-required="one" />
// <input type="text" rs-partially-required="two" />
// <input type="text" rs-partially-required="one" />
// <input type="text" rs-partially-required="null" />
// <input type="text" rs-partially-required="three" />
// <input type="text" rs-partially-required="three" />
// <input type="text" rs-partially-required="three" />
// In the above example, the first and fifth input are not required and can be submitted blank.
// The input with group "two" is the only one in the group, so just that input will be required by itself.
// The 2 inputs with "one" will be grouped together and one or the other will require an input before
// the form is valid. The same will be applied with group "three".
// For this form to be valid, group "two" will be required, and 1 input from group one will be required,
// and 1 input from group three will be required before this form can be valid.
You can add required attribute for each of them , and at the end , you can rely your validation on each/all/or just one of them
<form name="form" novalidate ng-submit="submit()">
// novalidate is form disabling your browser's own validation mechanism
<input type="text" required ng-model="texts.text1">
<input type="text" required ng-model="texts.text2">
<input type="text" required ng-model="texts.text3">
// you can do validation in variety of ways , but one of them is to disable your submit button until one of the textboxes are filled correctly like this :
<button type="submit" ng-disabled="form.text1.$invalid && form.text2.$invalid && form.text3.$invalid"></button>
</form>
This way if just one of them is filled , button will be enable
I don't know how you're gonna show that form is not valid , but I think desabling the submit button is the general way
I had similar grouping requirement in my project and I wrote this.Interested people can use this
.directive('group',function(){
return {
require: '^form',
link : function($scope,element,attrs,formCtrl){
var ctrls =[];
element.find(".group-member").each(function(){
var member = angular.element($(this));
var mdlCtrl = member.data("$ngModelController");
if(!mdlCtrl){
throw "Group member should have ng-model";
}
ctrls.push(mdlCtrl);
});
var errKey = attrs['name']+"GrpReqd";
var min = attrs['minRequired'] || 1;
var max = attrs['maxRequired'] || ctrls.length;
$scope.validateGroup = function(){
var defined=0;
for(i=0;i<ctrls.length;i++){
if(ctrls[i].$modelValue){
defined++;
}
}
if(defined < min || defined > max){
formCtrl.$setValidity(errKey,false);
} else {
formCtrl.$setValidity(errKey,true);
}
};
//support real time validation
angular.forEach(ctrls,function(mdlCtrl){
$scope.$watch(function () {
return mdlCtrl.$modelValue;
}, $scope.validateGroup);
});
}
};
})
HTML usage :
<div name="CancellationInfo" group min-required="1" max-required="1">
<input type="text" class="form-control group-member" style="width:100%;" name="Field1" ng-model="data.myField" />
<input type="text" class="form-control group-member" style="width:100%;" name="Field1" ng-model="data.myField2" />
<input type="text" class="form-control group-member" style="width:100%;" name="Field2" ng-model="data.myField3" />
</div>
Here group directive identifies the logical grouping. This directive sits on an element without ng-model, a div in the above example. group directive receives 2 optional attribute min-required and max-required. Group members are identified using group-member class on individual fields. Group members are supposed to have an ng-model for binding. Since group directive doesn't have an ng-model error will be emitted under yourForm.$error.CancellationInfoGrpReqd in the above case. Unique Error key is generated from the element name on which group directive is sitting with GrpReqd appended to it.

Javascript: Field validation

so i have been looking all over the internet for some simple javascript code that will let me give an alert when a field is empty and a different one when a # is not present. I keep finding regex, html and different plugins. I however need to do this in pure Javascript code. Any ideas how this could be done in a simple way?
And please, if you think this question doesn't belong here or is stupid, please point me to somewhere where i can find this information instead of insulting me. I have little to no experience with javascript.
function test(email, name) {
}
Here if you want to validate Email, use following code with given regex :
<input type="text" name="email" id="emailId" value="" >
<button onclick = "return ValidateEmail(document.getElementById('emailId').value)">Validate</button>
<script>
function ValidateEmail(inputText){
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.match(mailformat)) {
return true;
}
else {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
Or if you want to check the empty field, use following :
if(trim(document.getElementById('emailId').value)== ""){
alert("Field is empty")
}
// For #
var textVal = document.getElementById('emailId').value
if(textVal.indexOf("#") == -1){
alert(" # doesn't exist in input value");
}
Here is the fiddle : http://jsfiddle.net/TgNC5/
You have to find an object of element you want check (textbox etc).
<input type="text" name="email" id="email" />
In JS:
if(document.getElementById("email").value == "") { // test if it is empty
alert("E-mail empty");
}
This is really basic. Using regexp you can test, if it is real e-mail, or some garbage. I recommend reading something about JS and HTML.
function test_email(field_id, field_size) {
var field_value = $('#'+field_id+'').val();
error = false;
var pattern=/^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if(!pattern.test(field_value)){
error = true;
$('#'+field_id+'').attr('class','error_email');
}
return error;
}
This will check for empty string as well as for # symbol:
if(a=="")
alert("a is empty");
else if(a.indexOf("#")<0)
alert("a does not contain #");
You can do something like this:
var input = document.getElementById('email');
input.onblur = function() {
var value = input.value
if (value == "") {
alert("empty");
}
if (value.indexOf("#") == -1) {
alert("No # symbol");
}
}
see fiddle
Although this is not a solid soltuion for checking email addresses, please see the references below for a more detailed solution:
http://www.regular-expressions.info/email.html
http://www.codeproject.com/Tips/492632/Email-Validation-in-JavaScript
---- UPDATE ----
I have been made aware that there is no IE available to target, so the input field needs to be targeted like so:
document.getElementsByTagName("input")
Using this code will select all input fields present on the page. This is not what are looking for, we want to target a specific input field. The only way to do this without a class or ID is to selected it by key, like so:
document.getElementsByTagName("input")[0]
Without seeing all of your HTML it is impossible for me to know the correct key to use so you will need to count the amount of input fields on the page and the location of which your input field exists.
1st input filed = document.getElementsByTagName("input")[0]
2nd input filed = document.getElementsByTagName("input")[1]
3rd input filed = document.getElementsByTagName("input")[2]
4th input filed = document.getElementsByTagName("input")[3]
etc...
Hope this helps.

jQuery Validation conditional dependency: ensure text input matches value if radio button checked

I have a some form elements that follow a format like this:
<input type="radio" name="test" value="A"> <input type="text" size="3" name="weightA" id="A"><br>
<input type="radio" name="test" value="B"> <input type="text" size="3" name="weightB" id="B"><br>
I am using the jQuery Validation plugin to conduct client-side validation. What I would like to do with these fields is to ensure that the text input corresponding to the selected radio button equals 100. I have successfully implemented this on the server-side using PHP, but would like to add a JS method to give immediate feedback before the form is submitted. I have already included a jQuery range: rule to constrain user inputs in the two text fields within the numeric range [1-100].
How would I go about making this work? Would jQuery.validator.addMethod be the way to do it?
Edit: in response to Sparky's comment, I have attempted an addMethod, below:
$.validator.addMethod(
"selectWt", function(value, element) {
var selA = $('[name="test"]').val() === "A";
var selB = $('[name="test"]').val() === "B";
if (selA && ($("#A").val() !== "100")) {
return false;
} else if (selB && ($("#B").val() !== "100")) {
return false;
} else return true;
}, "Selected option must equal 100."
);
This seems to trigger the validation for #A but not #B, and the error message displayed is the one specified by the message: rule rather than the one specified by addMethod. Please bear in mind I have minimal programming background.
Try this:
DEMO: http://jsfiddle.net/maqZe/
$.validator.addMethod("selectWt", function (value, element) {
if ($(element).prev().is(':checked')) {
return ($(element).val() === 100);
} else {
return true;
}
}, "Selected option must equal 100.");
This rule can be applied generically. It simply checks to see if the radio element placed previous to element is checked. If so, it then returns true only if the text element's value is 100.
The way it's written, it only works if your type=text element immediately follows the type=radio element. It will need to be tweaked if you change the HTML arrangement.
It can also be made more flexible by passing in the 100 value as a parameter.
DEMO: http://jsfiddle.net/NFJUN/
$.validator.addMethod("selectWt", function (value, element, param) {
if ($(element).prev().is(':checked')) {
return ($(element).val() === param);
} else {
return true;
}
}, "Selected option must equal {0}.");
...
$('#myform').validate({ // initialize the plugin
rules: {
myfield: {
selectWt: 100 // use a parameter instead of "true"
},
}
});

Categories

Resources